Bluebird Promises Join behaviour

后端 未结 1 1267
难免孤独
难免孤独 2021-02-20 02:54

If I execute the following code with Node.js

var Promise = require(\'bluebird\');

Promise.join(
    function A() { console.log(\"A\"); },
    function B() { con         


        
1条回答
  •  生来不讨喜
    2021-02-20 03:21

    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.

    0 讨论(0)
提交回复
热议问题