0

I'm doing some slightly complex post processing on some mongoose documents and I ended up adding Q to help with managing the async. I can get things working but I'm a little confused by what's going on under the hood and why I get different behavior if I use a function to return the promise returned by Q.nfcall rather than just using Q.nfcall which returns a promise itself. The scenario I'm describing is probably clearer in code:

...
return Q.all([
    Q.nfcall(doc.save.bind(doc)),
    Q.nfcall(doc2.save.bind(doc2))
])
// confused on this line
.then(Q.nfcall(doc3.save.bind(doc3)))
.then(function(val) {
    console.log('val', val);
});

So this ends up logging an array which are the results of the Q.all promises. What I expect there is the results of the doc3 save since it comes later in the chain.

Now when I change the doc3 save to use an anonymous function like this:

...
return Q.all([
    Q.nfcall(doc.save.bind(doc)),
    Q.nfcall(doc2.save.bind(doc2))
])
// changed this line
.then(function() {
    return Q.nfcall(doc3.save.bind(doc3))
})
.then(function(val) {
    console.log('val', val);
});

I get the result I expect, namely that the val passed to the final then is the result from the doc3 save.

I feel like there is something big I'm missing. Isn't this code functionally equivalent?

Steve Hansell
  • 17,465
  • 1
  • 17
  • 14

1 Answers1

0

Without an anonymous function in your then(), the promise won't pass along the resolved data without ignoring anything else that's there. It preserves the ability to pass that data through more resolutions. The anonymous function allows you to accept the data as an argument and then do something more with it before proceeding.

adrichman
  • 1,215
  • 10
  • 17
  • So just always use anonymous functions for your thens? – matt.kauffman23 Apr 18 '14 at 18:37
  • Yes, though and exception *might* be if your alternative function returns a promise by design. The docs use anonymous functions but the section on __sequences__ demonstrates the alternative: https://github.com/kriskowal/q – adrichman Apr 18 '14 at 18:59