Thursday, 24 November 2016

async promises - just in time to be late for the node.js show

I'm late to the node.js show; and that's a good thing.

It means I don't have to worry about CPS callback hell

do_something(..., function(err, result) {
   something_else(result);
});

I means I don't even have to do much overt promising
do_something(...).then( (r) => {
  something_else(result);
}).catch( (e) => {
  ...
});

I can just use async/await with automatic exception propagation.
return await do_something(...);

I'm not averse to the odd promise for the interface between an old-style CPS function; after all only an async function can call await. But an async function is also a promise. So I can convert this:
function expressHandler(req, res, next) {
  do_something(..., function(err, result) {
    if (err) return next(err); // return avoids else
  ...
    next();
  });
} 
...
function do_something(..., callback) {
  try {
  ...
  return callback(undefined, result);
} catch (e) {
  return callback(e);
}

into
function expressHandler(req, res, next) {
  do_something(...).then((r) => {
    ...
    next();
  }).catch(next);
}
...
async function do_something(...) {
  return await something_else(...);
}

do_something is called as a promise and can be an async function that can await on other async functions or on promises. Async functions all the way up; callbacks all the way down (where I can't see).

No comments:

Post a comment