如果我使用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?
答案 0 :(得分:16)
Promise.join
将 promises 作为其所有参数,但最后一个参数,这是一个函数。
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更容易使用(并且性能更高),例如: / p>
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
});
这是有效的,因为请求已经在延迟返回之前发生,因为函数在同一范围内被调用。