If I execute the following code with Node.js
var Promise = require('bluebird');
Promise.join(
function A() { console.log("A"); },
function B() { console.log("B"); }
).done(
function done() { console.log("done");}
);
The console will log
B
done
However I would expect
A
B
done
or
B
A
done
If it set a break point in function A it is never reached. Why is it that it processes B but not A?
Promise.join
takes promises as all its arguments but its last one, which is a function.
Promise.join(Promise.delay(100), request("http://...com"), function(_, res){
// 100 ms have passed and the request has returned.
});
You're feeding it two functions so it does the following:
function A() { ... }
- basically returning a promise over itfunction B() {... }
logging it.See the docs:
Promise.join(Promise|Thenable|value promises..., Function handler) -> Promise
For coordinating multiple concurrent discrete promises. While .all() is good for handling a dynamically sized list of uniform promises, Promise.join is much easier (and more performant) to use when you have a fixed amount of discrete promises that you want to coordinate concurrently, for example:
var Promise = require("bluebird");
var join = Promise.join;
join(getPictures(), getComments(), getTweets(),
function(pictures, comments, tweets) {
console.log("in total: " + pictures.length + comments.length + tweets.length);
});
Update:
JSRishe came up with another clever way to solve this sort of pattern in this answer which looks something like:
Promise.delay(100).return(request("http://...com").then(function(res){
// 100 ms have passed and the request has returned
});
This works because the request already happens before the delay returns since the function is called in the same scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With