所以,我有一个带有如下 promise 链的函数:
Myclass.Prototype.initAsync = function() {
someFunctionAsync(params).bind(this)
.then(function(data) {
processData(data);
return someOtherFunctionAsync(params).bind(this);
})
.then(function(data) {
processData(data);
return yetAnotherFunctionAsync(params).bind(this);
})
.finally(function(data) {
processData(data);
});
}
它有效,但我希望这个函数本身能够位于 promise 链中。通常,我只是去掉最后的“finally”,但我不希望调用者负责调用 processData。我希望能够像这样调用这个函数:
setupFunctionAsync(params).bind(this)
.then(function(data) {
processSetup();
return initAsync();
})
.finally(function(data) {
runProgram();
});
在 initAsync 的“finally”中,正确的做法是什么?我想用 Promise.new 创建一个新的空 promise 并返回它吗?或者我想将 Promise.method 与空方法一起使用?或者有更好的办法吗?
现在我正在做以下事情,但我想知道这是否是最好的事情:
return someFunctionAsync(params).bind(this)
.then(function(data) {
...
.then(function(data) {
processData(data);
return new Promise(function(resolve, reject) { resolve(); });
});
<小时/>
最新更新:
阅读了一些答案后,这行得通吗?
Myclass.Prototype.initAsync = function() {
return someFunctionAsync(params).bind(this)
.then(function(data) {
processData(data);
return someOtherFunctionAsync(params).bind(this);
})
.then(function(data) {
processData(data);
return yetAnotherFunctionAsync(params).bind(this);
})
.then(function(data) {
processData(data);
});
}
它的名字是这样的:
this.initAsync()
.then(function() {
runProgram();
});
请注意,我在 initAsync 的最后一个 then 中没有“返回”。这样可以吗?
最佳答案
我认为你终于误解了
。传递给finally
的函数在任何情况下都会被调用,这意味着无论是在promise被解决时还是在被拒绝时。 finally
还返回另一个 Promise(具有前一个 Promise 的值),因此链接没有问题。
看起来很像您应该使用then
,而您只使用finally
,因为它似乎很适合该过程的最后一步。您可以在这里使用then
。
无论如何,由于 finally
已经返回了一个 Promise,您只需在函数的开头添加一个 return
即可。您不需要“虚假 promise ”。
在最后一个 then
传递的函数中没有 return 语句不是问题。它只是意味着没有值传递给 then
之后链接的下一个 Promise。然而,无论如何它都会被调用。您添加到问题中的代码看起来很好。
关于javascript - 在 Node.js 中让方法返回 Bluebird 的虚拟 promise 的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35045360/