2016-08-22 5 views
1

私は、約束の結果(ネスティングの約束)をどのようにフォワードするかを理解することに問題があります。プロミスチェーンの結果を転送する - 拒否された値の代わりにプロミスオブジェクトを取得する理由

このコードは(最終的に、私は整数値を取得します)私は期待どおりに動作:

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

だから私は、私はrejectresolveを変更した場合、私は同様の結果を得るでしょうと思いました(整数値ですが、倍精度* 2の乗算を伴わない)。しかし、私は完全な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約束がresolveが行ったようyetAnotherNestedPromiseから返された "アンラップ" しないのですか?

答えて

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); 
    }); 
関連する問題