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?