2016-08-22 68 views
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))

所以我想,如果我改變resolvereject我會得到類似的結果(整數值,但沒有雙倍* 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沒有回來?

回答

2

因爲它不應該首先收到Promise

reject回調應該包含原因失敗(即Error)。

function opThatResolves() { 
    return Promise.resolve(1); 
} 

function opThatWillBeForwarded(x) { 
    return new Promise(function(resolve, reject) { 
    reject(new Error("failed")); 
    }) 
} 

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)); 

注意,錯誤可以通過後續的錯誤回調重新拋出:

new Promise((resolve, reject) => { 
    reject(new Error("failed !")); 
}) 
    .then(null, reason => { 
     console.log(1, reason); 
     throw reason; 
    }) 
    .catch(reason => { 
     console.log(2, reason); 
    }); 

還要注意的是,如果一個錯誤回調未能再次引發錯誤(或拋出另一個錯誤),隨後then的方法將推出成功回調:

new Promise((resolve, reject) => { 
    reject(new Error("failed !")); 
}) 
    .then(null, reason => { 
     console.log(1, reason); 
    }) 
    .then(result => { 
     console.log("Success! Let's throw something else..."); 
     throw new Error("Another failure"); 
    }) 
    .catch(reason => { 
     console.log(2, reason); 
    }); 
相關問題