I\'m trying to understand how promise chaining works. I\'m using q.js. Here\'s what I\'m playing with.
var Q = require(\"q\"); // npm install q
// the functio
It's because then
doesn't expect another promise as an argument. Rather it expects handler functions, an callback and/or an errback, the former you are passing in your 2nd example. Indeed any argument that is not a function is simply ignored.
From the docs:
If you return a value in a handler, outputPromise will get fulfilled.
If you throw an exception in a handler, outputPromise will get rejected.
If you return a promise in a handler, outputPromise will “become” that promise. Being able to become a new promise is useful for managing delays, combining results, or recovering from errors.
So yes, chaining promises can be done. You're doing it right in your 2nd example.
It's possible that the contrived example here of passing fulfilled promises makes the way chaining promises works seem overly verbose, but in real world usage, you typically chain promises because you're interested in their return values, e.g.:
somethingAsync().then(function (n) {
return somethingElseAsync(n);
})
.then(function (n) {
return somethingElseAsync(n);
})
.then(function (result) {
// ...
})
(Actually this mirrors async.waterfall
. If you just wanted to call a series of async functions in order with no regards to their results you could use async.series
)