【问题标题】:Bluebird Promises Join behaviour蓝鸟承诺加入行为
【发布时间】:2014-11-08 15:39:18
【问题描述】:

如果我用 Node.js 执行以下代码

var Promise = require('bluebird');

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

控制台会记录

B
done

但我希望

A
B
done

B
A
done

如果它在函数 A 中设置断点,则永远不会到达。为什么它只处理B而不处理A?

【问题讨论】:

    标签: javascript node.js promise bluebird


    【解决方案1】:

    Promise.joinpromises 作为所有参数,但最后一个是函数。

    Promise.join(Promise.delay(100), request("http://...com"), function(_, res){
           // 100 ms have passed and the request has returned.
    });
    

    你给它提供了两个函数,所以它执行以下操作:

    • function A() { ... } 上做出承诺 - 基本上是在它上面返回一个承诺
    • 完成后(立即)执行最后一个参数,function B() {... } 记录它。

    查看文档:

    Promise.join(Promise|Thenable|value promises..., Function handler) -> Promise

    用于协调多个并发的离散承诺。虽然 .all() 适合处理动态大小的统一承诺列表,但当您有固定数量的要同时协调的离散承诺时,Promise.join 更容易使用(并且性能更高),例如:

    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);

    });


    更新:

    JSRishe 想出了另一种巧妙的方法来解决这种模式in this answer,它看起来像:

    Promise.delay(100).return(request("http://...com").then(function(res){
        // 100 ms have passed and the request has returned 
    });
    

    这是有效的,因为请求已经在延迟返回之前发生,因为该函数是在同一范围内调用的。

    【讨论】:

    • .join() 有什么是.all() 做不到的吗?还是只是语法不同?
    • @jfriend00 Promise.join(p1, p2,..., pn, fn) 的行为类似于 Promise.all([p1, p2, ..., pn]).spread(fn),只是速度稍快一些。这对于固定数量的 Promise 很有用,并且是使用 Promise 作为代理的好糖:var p1 = asyncOp(); var p2 = p1.then(otherOp); var p3 = p2.then(oneMore); Promise.join(p1, p2, p3, function(r1, r2, r3){ ...。它的另一个优势是 TypeScript 等语言中更好的类型信息,因为它更容易进行静态分析。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 2014-02-13
    • 2014-11-06
    • 2015-09-06
    相关资源
    最近更新 更多