asynquence API

To start off, the way you create a sequence (an asynquence instance) is with the ASQ(..) function. An ASQ() call with no parameters creates an empty initial sequence, whereas passing one or more values or functions to ASQ(..) sets up the sequence with each argument representing the initial steps of the sequence.

Note: For the purposes of all code examples here, I will use the asynquence top-level identifier in global browser usage: ASQ. If you include and use asynquence through a module system (browser or server), you of course can define whichever symbol you prefer, and asynquence won’t care!

Many of the API methods discussed here are built into the core of asynquence, but others are provided through including the optional “contrib” plug-ins package. See the documentation for asynquence for whether a method is built in or defined via plug-in: http://github.com/getify/asynquence

Steps

If a function represents a normal step in the sequence, that function is invoked with the first parameter being the continuation callback, and any subsequent parameters being any messages passed on from the previous step. The step will not complete until the continuation callback is called. Once it’s called, any arguments you pass to it will be sent along as messages to the next step in the sequence.

To add an additional normal step to the sequence, call then(..) (which has essentially the exact same semantics as the ASQ(..) call):

  1. ASQ(
  2. // step 1
  3. function(done){
  4. setTimeout( function(){
  5. done( "Hello" );
  6. }, 100 );
  7. },
  8. // step 2
  9. function(done,greeting) {
  10. setTimeout( function(){
  11. done( greeting + " World" );
  12. }, 100 );
  13. }
  14. )
  15. // step 3
  16. .then( function(done,msg){
  17. setTimeout( function(){
  18. done( msg.toUpperCase() );
  19. }, 100 );
  20. } )
  21. // step 4
  22. .then( function(done,msg){
  23. console.log( msg ); // HELLO WORLD
  24. } );

Note: Though the name then(..) is identical to the native Promises API, this then(..) is different. You can pass as few or as many functions or values to then(..) as you’d like, and each is taken as a separate step. There’s no two-callback fulfilled/rejected semantics involved.

Unlike with Promises, where to chain one Promise to the next you have to create and return that Promise from a then(..) fulfillment handler, with asynquence, all you need to do is call the continuation callback — I always call it done() but you can name it whatever suits you — and optionally pass it completion messages as arguments.

Each step defined by then(..) is assumed to be asynchronous. If you have a step that’s synchronous, you can either just call done(..) right away, or you can use the simpler val(..) step helper:

  1. // step 1 (sync)
  2. ASQ( function(done){
  3. done( "Hello" ); // manually synchronous
  4. } )
  5. // step 2 (sync)
  6. .val( function(greeting){
  7. return greeting + " World";
  8. } )
  9. // step 3 (async)
  10. .then( function(done,msg){
  11. setTimeout( function(){
  12. done( msg.toUpperCase() );
  13. }, 100 );
  14. } )
  15. // step 4 (sync)
  16. .val( function(msg){
  17. console.log( msg );
  18. } );

As you can see, val(..)-invoked steps don’t receive a continuation callback, as that part is assumed for you — and the parameter list is less cluttered as a result! To send a message along to the next step, you simply use return.

Think of val(..) as representing a synchronous “value-only” step, which is useful for synchronous value operations, logging, and the like.

Errors

One important difference with asynquence compared to Promises is with error handling.

With Promises, each individual Promise (step) in a chain can have its own independent error, and each subsequent step has the ability to handle the error or not. The main reason for this semantic comes (again) from the focus on individual Promises rather than on the chain (sequence) as a whole.

I believe that most of the time, an error in one part of a sequence is generally not recoverable, so the subsequent steps in the sequence are moot and should be skipped. So, by default, an error at any step of a sequence throws the entire sequence into error mode, and the rest of the normal steps are ignored.

If you do need to have a step where its error is recoverable, there are several different API methods that can accommodate, such as try(..) — previously mentioned as a kind of try..catch step — or until(..) — a retry loop that keeps attempting the step until it succeeds or you manually break() the loop. asynquence even has pThen(..) and pCatch(..) methods, which work identically to how normal Promise then(..) and catch(..) work (see Chapter 3), so you can do localized mid-sequence error handling if you so choose.

The point is, you have both options, but the more common one in my experience is the default. With Promises, to get a chain of steps to ignore all steps once an error occurs, you have to take care not to register a rejection handler at any step; otherwise, that error gets swallowed as handled, and the sequence may continue (perhaps unexpectedly). This kind of desired behavior is a bit awkward to properly and reliably handle.

To register a sequence error notification handler, asynquence provides an or(..) sequence method, which also has an alias of onerror(..). You can call this method anywhere in the sequence, and you can register as many handlers as you’d like. That makes it easy for multiple different consumers to listen in on a sequence to know if it failed or not; it’s kind of like an error event handler in that respect.

Just like with Promises, all JS exceptions become sequence errors, or you can programmatically signal a sequence error:

  1. var sq = ASQ( function(done){
  2. setTimeout( function(){
  3. // signal an error for the sequence
  4. done.fail( "Oops" );
  5. }, 100 );
  6. } )
  7. .then( function(done){
  8. // will never get here
  9. } )
  10. .or( function(err){
  11. console.log( err ); // Oops
  12. } )
  13. .then( function(done){
  14. // won't get here either
  15. } );
  16. // later
  17. sq.or( function(err){
  18. console.log( err ); // Oops
  19. } );

Another really important difference with error handling in asynquence compared to native Promises is the default behavior of “unhandled exceptions”. As we discussed at length in Chapter 3, a rejected Promise without a registered rejection handler will just silently hold (aka swallow) the error; you have to remember to always end a chain with a final catch(..).

In asynquence, the assumption is reversed.

If an error occurs on a sequence, and it at that moment has no error handlers registered, the error is reported to the console. In other words, unhandled rejections are by default always reported so as not to be swallowed and missed.

As soon as you register an error handler against a sequence, it opts that sequence out of such reporting, to prevent duplicate noise.

There may, in fact, be cases where you want to create a sequence that may go into the error state before you have a chance to register the handler. This isn’t common, but it can happen from time to time.

In those cases, you can also opt a sequence instance out of error reporting by calling defer() on the sequence. You should only opt out of error reporting if you are sure that you’re going to eventually handle such errors:

  1. var sq1 = ASQ( function(done){
  2. doesnt.Exist(); // will throw exception to console
  3. } );
  4. var sq2 = ASQ( function(done){
  5. doesnt.Exist(); // will throw only a sequence error
  6. } )
  7. // opt-out of error reporting
  8. .defer();
  9. setTimeout( function(){
  10. sq1.or( function(err){
  11. console.log( err ); // ReferenceError
  12. } );
  13. sq2.or( function(err){
  14. console.log( err ); // ReferenceError
  15. } );
  16. }, 100 );
  17. // ReferenceError (from sq1)

This is better error handling behavior than Promises themselves have, because it’s the Pit of Success, not the Pit of Failure (see Chapter 3).

Note: If a sequence is piped into (aka subsumed by) another sequence — see “Combining Sequences” for a complete description — then the source sequence is opted out of error reporting, but now the target sequence’s error reporting or lack thereof must be considered.

Parallel Steps

Not all steps in your sequences will have just a single (async) task to perform; some will need to perform multiple steps “in parallel” (concurrently). A step in a sequence in which multiple substeps are processing concurrently is called a gate(..) — there’s an all(..) alias if you prefer — and is directly symmetric to native Promise.all([..]).

If all the steps in the gate(..) complete successfully, all success messages will be passed to the next sequence step. If any of them generate errors, the whole sequence immediately goes into an error state.

Consider:

  1. ASQ( function(done){
  2. setTimeout( done, 100 );
  3. } )
  4. .gate(
  5. function(done){
  6. setTimeout( function(){
  7. done( "Hello" );
  8. }, 100 );
  9. },
  10. function(done){
  11. setTimeout( function(){
  12. done( "World", "!" );
  13. }, 100 );
  14. }
  15. )
  16. .val( function(msg1,msg2){
  17. console.log( msg1 ); // Hello
  18. console.log( msg2 ); // [ "World", "!" ]
  19. } );

For illustration, let’s compare that example to native Promises:

  1. new Promise( function(resolve,reject){
  2. setTimeout( resolve, 100 );
  3. } )
  4. .then( function(){
  5. return Promise.all( [
  6. new Promise( function(resolve,reject){
  7. setTimeout( function(){
  8. resolve( "Hello" );
  9. }, 100 );
  10. } ),
  11. new Promise( function(resolve,reject){
  12. setTimeout( function(){
  13. // note: we need a [ ] array here
  14. resolve( [ "World", "!" ] );
  15. }, 100 );
  16. } )
  17. ] );
  18. } )
  19. .then( function(msgs){
  20. console.log( msgs[0] ); // Hello
  21. console.log( msgs[1] ); // [ "World", "!" ]
  22. } );

Yuck. Promises require a lot more boilerplate overhead to express the same asynchronous flow control. That’s a great illustration of why the asynquence API and abstraction make dealing with Promise steps a lot nicer. The improvement only goes higher the more complex your asynchrony is.

Step Variations

There are several variations in the contrib plug-ins on asynquence‘s gate(..) step type that can be quite helpful:

  • any(..) is like gate(..), except just one segment has to eventually succeed to proceed on the main sequence.
  • first(..) is like any(..), except as soon as any segment succeeds, the main sequence proceeds (ignoring subsequent results from other segments).
  • race(..) (symmetric with Promise.race([..])) is like first(..), except the main sequence proceeds as soon as any segment completes (either success or failure).
  • last(..) is like any(..), except only the latest segment to complete successfully sends its message(s) along to the main sequence.
  • none(..) is the inverse of gate(..): the main sequence proceeds only if all the segments fail (with all segment error message(s) transposed as success message(s) and vice versa).

Let’s first define some helpers to make illustration cleaner:

  1. function success1(done) {
  2. setTimeout( function(){
  3. done( 1 );
  4. }, 100 );
  5. }
  6. function success2(done) {
  7. setTimeout( function(){
  8. done( 2 );
  9. }, 100 );
  10. }
  11. function failure3(done) {
  12. setTimeout( function(){
  13. done.fail( 3 );
  14. }, 100 );
  15. }
  16. function output(msg) {
  17. console.log( msg );
  18. }

Now, let’s demonstrate these gate(..) step variations:

  1. ASQ().race(
  2. failure3,
  3. success1
  4. )
  5. .or( output ); // 3
  6. ASQ().any(
  7. success1,
  8. failure3,
  9. success2
  10. )
  11. .val( function(){
  12. var args = [].slice.call( arguments );
  13. console.log(
  14. args // [ 1, undefined, 2 ]
  15. );
  16. } );
  17. ASQ().first(
  18. failure3,
  19. success1,
  20. success2
  21. )
  22. .val( output ); // 1
  23. ASQ().last(
  24. failure3,
  25. success1,
  26. success2
  27. )
  28. .val( output ); // 2
  29. ASQ().none(
  30. failure3
  31. )
  32. .val( output ) // 3
  33. .none(
  34. failure3
  35. success1
  36. )
  37. .or( output ); // 1

Another step variation is map(..), which lets you asynchronously map elements of an array to different values, and the step doesn’t proceed until all the mappings are complete. map(..) is very similar to gate(..), except it gets the initial values from an array instead of from separately specified functions, and also because you define a single function callback to operate on each value:

  1. function double(x,done) {
  2. setTimeout( function(){
  3. done( x * 2 );
  4. }, 100 );
  5. }
  6. ASQ().map( [1,2,3], double )
  7. .val( output ); // [2,4,6]

Also, map(..) can receive either of its parameters (the array or the callback) from messages passed from the previous step:

  1. function plusOne(x,done) {
  2. setTimeout( function(){
  3. done( x + 1 );
  4. }, 100 );
  5. }
  6. ASQ( [1,2,3] )
  7. .map( double ) // message `[1,2,3]` comes in
  8. .map( plusOne ) // message `[2,4,6]` comes in
  9. .val( output ); // [3,5,7]

Another variation is waterfall(..), which is kind of like a mixture between gate(..)‘s message collection behavior but then(..)‘s sequential processing.

Step 1 is first executed, then the success message from step 1 is given to step 2, and then both success messages go to step 3, and then all three success messages go to step 4, and so on, such that the messages sort of collect and cascade down the “waterfall”.

Consider:

  1. function double(done) {
  2. var args = [].slice.call( arguments, 1 );
  3. console.log( args );
  4. setTimeout( function(){
  5. done( args[args.length - 1] * 2 );
  6. }, 100 );
  7. }
  8. ASQ( 3 )
  9. .waterfall(
  10. double, // [ 3 ]
  11. double, // [ 6 ]
  12. double, // [ 6, 12 ]
  13. double // [ 6, 12, 24 ]
  14. )
  15. .val( function(){
  16. var args = [].slice.call( arguments );
  17. console.log( args ); // [ 6, 12, 24, 48 ]
  18. } );

If at any point in the “waterfall” an error occurs, the whole sequence immediately goes into an error state.

Error Tolerance

Sometimes you want to manage errors at the step level and not let them necessarily send the whole sequence into the error state. asynquence offers two step variations for that purpose.

try(..) attempts a step, and if it succeeds, the sequence proceeds as normal, but if the step fails, the failure is turned into a success message formated as { catch: .. } with the error message(s) filled in:

  1. ASQ()
  2. .try( success1 )
  3. .val( output ) // 1
  4. .try( failure3 )
  5. .val( output ) // { catch: 3 }
  6. .or( function(err){
  7. // never gets here
  8. } );

You could instead set up a retry loop using until(..), which tries the step and if it fails, retries the step again on the next event loop tick, and so on.

This retry loop can continue indefinitely, but if you want to break out of the loop, you can call the break() flag on the completion trigger, which sends the main sequence into an error state:

  1. var count = 0;
  2. ASQ( 3 )
  3. .until( double )
  4. .val( output ) // 6
  5. .until( function(done){
  6. count++;
  7. setTimeout( function(){
  8. if (count < 5) {
  9. done.fail();
  10. }
  11. else {
  12. // break out of the `until(..)` retry loop
  13. done.break( "Oops" );
  14. }
  15. }, 100 );
  16. } )
  17. .or( output ); // Oops

Promise-Style Steps

If you would prefer to have, inline in your sequence, Promise-style semantics like Promises’ then(..) and catch(..) (see Chapter 3), you can use the pThen and pCatch plug-ins:

  1. ASQ( 21 )
  2. .pThen( function(msg){
  3. return msg * 2;
  4. } )
  5. .pThen( output ) // 42
  6. .pThen( function(){
  7. // throw an exception
  8. doesnt.Exist();
  9. } )
  10. .pCatch( function(err){
  11. // caught the exception (rejection)
  12. console.log( err ); // ReferenceError
  13. } )
  14. .val( function(){
  15. // main sequence is back in a
  16. // success state because previous
  17. // exception was caught by
  18. // `pCatch(..)`
  19. } );

pThen(..) and pCatch(..) are designed to run in the sequence, but behave as if it was a normal Promise chain. As such, you can either resolve genuine Promises or asynquence sequences from the “fulfillment” handler passed to pThen(..) (see Chapter 3).

Forking Sequences

One feature that can be quite useful about Promises is that you can attach multiple then(..) handler registrations to the same promise, effectively “forking” the flow-control at that promise:

  1. var p = Promise.resolve( 21 );
  2. // fork 1 (from `p`)
  3. p.then( function(msg){
  4. return msg * 2;
  5. } )
  6. .then( function(msg){
  7. console.log( msg ); // 42
  8. } )
  9. // fork 2 (from `p`)
  10. p.then( function(msg){
  11. console.log( msg ); // 21
  12. } );

The same “forking” is easy in asynquence with fork():

  1. var sq = ASQ(..).then(..).then(..);
  2. var sq2 = sq.fork();
  3. // fork 1
  4. sq.then(..)..;
  5. // fork 2
  6. sq2.then(..)..;

Combining Sequences

The reverse of fork()ing, you can combine two sequences by subsuming one into another, using the seq(..) instance method:

  1. var sq = ASQ( function(done){
  2. setTimeout( function(){
  3. done( "Hello World" );
  4. }, 200 );
  5. } );
  6. ASQ( function(done){
  7. setTimeout( done, 100 );
  8. } )
  9. // subsume `sq` sequence into this sequence
  10. .seq( sq )
  11. .val( function(msg){
  12. console.log( msg ); // Hello World
  13. } )

seq(..) can either accept a sequence itself, as shown here, or a function. If a function, it’s expected that the function when called will return a sequence, so the preceding code could have been done with:

  1. // ..
  2. .seq( function(){
  3. return sq;
  4. } )
  5. // ..

Also, that step could instead have been accomplished with a pipe(..):

  1. // ..
  2. .then( function(done){
  3. // pipe `sq` into the `done` continuation callback
  4. sq.pipe( done );
  5. } )
  6. // ..

When a sequence is subsumed, both its success message stream and its error stream are piped in.

Note: As mentioned in an earlier note, piping (manually with pipe(..) or automatically with seq(..)) opts the source sequence out of error-reporting, but doesn’t affect the error reporting status of the target sequence.