Promises and Callbacks

I think asynquence sequences provide a lot of value on top of native Promises, and for the most part you’ll find it more pleasant and more powerful to work at that level of abstraction. However, integrating asynquence with other non-asynquence code will be a reality.

You can easily subsume a promise (e.g., thenable — see Chapter 3) into a sequence using the promise(..) instance method:

  1. var p = Promise.resolve( 42 );
  2. ASQ()
  3. .promise( p ) // could also: `function(){ return p; }`
  4. .val( function(msg){
  5. console.log( msg ); // 42
  6. } );

And to go the opposite direction and fork/vend a promise from a sequence at a certain step, use the toPromise contrib plug-in:

  1. var sq = ASQ.after( 100, "Hello World" );
  2. sq.toPromise()
  3. // this is a standard promise chain now
  4. .then( function(msg){
  5. return msg.toUpperCase();
  6. } )
  7. .then( function(msg){
  8. console.log( msg ); // HELLO WORLD
  9. } );

To adapt asynquence to systems using callbacks, there are several helper facilities. To automatically generate an “error-first style” callback from your sequence to wire into a callback-oriented utility, use errfcb:

  1. var sq = ASQ( function(done){
  2. // note: expecting "error-first style" callback
  3. someAsyncFuncWithCB( 1, 2, done.errfcb )
  4. } )
  5. .val( function(msg){
  6. // ..
  7. } )
  8. .or( function(err){
  9. // ..
  10. } );
  11. // note: expecting "error-first style" callback
  12. anotherAsyncFuncWithCB( 1, 2, sq.errfcb() );

You also may want to create a sequence-wrapped version of a utility — compare to “promisory” in Chapter 3 and “thunkory” in Chapter 4 — and asynquence provides ASQ.wrap(..) for that purpose:

  1. var coolUtility = ASQ.wrap( someAsyncFuncWithCB );
  2. coolUtility( 1, 2 )
  3. .val( function(msg){
  4. // ..
  5. } )
  6. .or( function(err){
  7. // ..
  8. } );

Note: For the sake of clarity (and for fun!), let’s coin yet another term, for a sequence-producing function that comes from ASQ.wrap(..), like coolUtility here. I propose “sequory” (“sequence” + “factory”).