[英]Bluebird promise - then after finally
我在Bluebird / Promises中遇到了一些問題。 對於Promise1,如果調用fullfill或reject,一切正常。 但是當我們在finally塊中返回Promise2時,它只適用於reject和fullfil,我們在后面的回調中得到了未定義。
function getPromise1() {
return new Promise(function(fulfill, reject) {
fulfill("OK1");
});
}
function getPromise2() {
return new Promise(function(fulfill, reject) {
fulfill("OK2");
});
}
getPromise1()
.then(function(c){
console.log(c);
})
.catch(function(e) {
console.log(e);
})
.finally(function() {
return getPromise2();
})
.then(function(c){
console.log(c);
})
.catch(function(e) {
console.log(e);
});
輸出:
OK1
未定義
finally
塊不會更改返回值。
.finally()有一些特殊的語義,因為無法從處理程序修改最終值。
Bluebird將等待它,但它不會改變返回值(這是一個自以為是的選擇並與提議的ECMAScript標准語義保持一致 - finally
在某些語言中與其他語言不同)。
如果你想鏈接一個處理程序而不管先前的promise的結果,你可以使用.reflect()將結果轉換為PromiseInspection 。
官方文檔在這里 ,雖然在撰寫本文時它並沒有真正使用這個用例。
更好的例子:
Promise.resolve("OK1")
.then(function(x) {
console.log(x); // outputs OK1
return Promise.reject("Rejection demo");
})
.reflect()
.then(function(settled) {
if (settled.isRejected()) {
// outputs Rejected: Rejection demo
console.log("Rejected:", settled.reason());
}
if (settled.isFulfilled()) {
console.log("Fulfilled:", settled.value()); // skipped
}
return Promise.resolve("OK2");
})
.then(function(c){
console.log(c); // outputs OK2
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.