Bluebird Promises Join behaviour

我是研究僧i 提交于 2019-12-04 01:57:05
Benjamin Gruenbaum

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!