Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bluebird Promises Join behaviour

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?

like image 739
Udo Klein Avatar asked Sep 15 '14 07:09

Udo Klein


1 Answers

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:

  • Make a promise over function A() { ... } - basically returning a promise over it
  • When it's done (immediately) execute the last argument, function 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.

like image 194
Benjamin Gruenbaum Avatar answered Sep 30 '22 14:09

Benjamin Gruenbaum