1
我在理解轉發承諾結果(嵌套承諾)如何工作時遇到問題。轉發承諾導致Promise鏈 - 爲什麼我得到Promise對象而不是被拒絕的值
此代碼的工作,因爲我預計(在最終然後我得到的整數值):
function opThatResolves() {
return Promise.resolve(1);
}
function opThatWillBeForwarded(x) {
return new Promise(function(resolve, reject) {
resolve(yetAnotherNestedPromise(x));
})
}
function yetAnotherNestedPromise(x) {
return Promise.resolve(-x);
}
opThatResolves()
.then(x => opThatWillBeForwarded(x))
.then(x => x * 2)
.then(x => x * 2)
.then(x => console.log("Resolved: " + x))
.catch(x => console.log("Rejected: " + x))
所以我想,如果我改變resolve
到reject
我會得到類似的結果(整數值,但沒有雙倍* 2乘法)在catch塊中。不過,我得到一個完整的Promise
對象:
function opThatResolves() {
return Promise.resolve(1);
}
function opThatWillBeForwarded(x) {
return new Promise(function(resolve, reject) {
reject(yetAnotherNestedPromise(x));
})
}
function yetAnotherNestedPromise(x) {
return Promise.resolve(-x);
}
opThatResolves()
.then(x => opThatWillBeForwarded(x))
.then(x => x * 2)
.then(x => x * 2)
.then(x => console.log("Resolved: " + x))
.catch(x => console.log("Rejected: " + x))
爲什麼reject
不 「解包」 無極從yetAnotherNestedPromise
就像resolve
沒有回來?