我正在尝试了解 promise 链的工作原理。我正在使用 q.js .这就是我正在玩的东西。
var Q = require("q"); // npm install q
// the function Q(value) returns a fulfilled promise with the value... I think.
Q(1).then(Q(2)).then(Q(3)).then(Q(4)).then(function(n) {
console.log(n);
});
Q(1).then(function(n) {
return Q(2);
}).then(function(n) {
return Q(3);
}).then(function(n) {
return Q(4);
}).then(function(n) {
console.log("done: " + n);
});
我的问题基本上归结为为什么第一个记录 1
而后一个记录我所期望的并且基本上记录 1 到 4。我曾希望第一个记录 4
而不是 1
。
我真的只是希望能够有一些返回 promise 的方法,然后像时尚的瀑布一样将它们链接在一起 - 我想我可以使用 async和瀑布,但只是想知道这是否可以通过 promise 实现。
最佳答案
这是因为 then
不期望另一个 promise 作为参数。相反,它需要处理程序函数、一个回调 和/或一个errback,这是您在第二个示例中传递的前者。 Indeed any argument that is not a function is simply ignored .
If you return a value in a handler, outputPromise will get fulfilled.
If you throw an exception in a handler, outputPromise will get rejected.
If you return a promise in a handler, outputPromise will “become” that promise. Being able to become a new promise is useful for managing delays, combining results, or recovering from errors.
所以是的,可以实现链接 promise 。您在第二个示例中做对了。
这里传递已实现的 promise 的人为示例可能使链接 promise 的工作方式看起来过于冗长,但在现实世界的使用中,您通常会链接 promise ,因为您对它们的返回值感兴趣,例如:
somethingAsync().then(function (n) {
return somethingElseAsync(n);
})
.then(function (n) {
return somethingElseAsync(n);
})
.then(function (result) {
// ...
})
(实际上 this 反射(reflect)了 async.waterfall
。如果你只是想按顺序调用一系列异步函数而不考虑它们的结果,你可以使用 异步系列
)
关于javascript - 使用 q.js 链接 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20074685/