Search code examples
javascriptnode.jspromisewhen-js

Converting node async code to promises


I'm experimenting with promises - namely when.js - and want to convert some test code - a little unclear how to do it even after reading docs. My experiments so far have been far messier than standard callback pyramids so I think I am missing some shortcut.

Here's my sample code I would like to replicate:

Async1(function(err, res) {
  res++;
  Async2(res, function(error, result) {
    done();
  })
})

Solution

  • nodefn.call(Async2, nodefn.call(Async1)).ensure(done);
    

    Here, Async2 actually gets called synchronously and with the Promise for Async1() as an argument - it doesn't wait for Async1 to resolve. To chain them, you would need to use

    nodefn.call(Async1).then(nodefn.lift(Async2)).ensure(done);
    // which is equivalent to:
    nodefn.call(Async1).then(function(result) {
        return nodefn.call(Async2, result);
    }).ensure(done);
    

    I want to perform some logic between the 2 calls

    Then you would need to put another function in the chain, or modify one of the functions in the chain:

    nodefn.call(Async1)
      .then(function(res){return res+1;}) // return modified result
      .then(nodefn.lift(Async2))
      .ensure(done);
    // or just
    nodefn.call(Async1).then(function(res) {
        res++; // do whatever you want
        return nodefn.call(Async2, res);
    }).ensure(done);