2

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();
  })
})
cyberwombat
  • 38,105
  • 35
  • 175
  • 251
  • Do you have problems with formulating `Async1().then(function(res){return Async2(res+1)}).then(done)` or with adapting the `Async` functions? Then you'd need to show us their code… – Bergi Jul 03 '13 at 18:23
  • I have nodefn.call(Async2, nodefn.call(Async1)).ensure(done); but not sure where I would do res++ - it's actually just a placeholder - I want to perform some logic between the 2 calls – cyberwombat Jul 03 '13 at 19:06

2 Answers2

3
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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Not sure about When but with Deferred library you do it like that:

// One time configuration of promise versions
async1 = promisify(async1);
async2 = promisify(async2);

// construct flow
async1().then(function (res) { return async2(++res); }).done();
Mariusz Nowak
  • 32,050
  • 5
  • 35
  • 37