2017-02-28 93 views
0

請考慮此代碼。假設first catch塊得到執行,那麼問題是如何確定它是由testP還是first then承諾造成的。承諾代碼中的衝突

var testP = function(){ 
    return new Promise(function(resolve, reject){ 
     //reject or resolve 
    }); 
} 

testP().then(function(res){ 
    console.log("first then"); 
    console.log(res); 
    return new Promise(function(resolve,reject){ 
     // reject or resolve 
    }) 
}) 
.catch(function(err){ 
    console.log("first catch"); 
    console.log(err); 
}) 

回答

0

你不能。

如果你想區分?你應該使用第二個參數then

testP().then(function(res){ 
    console.log("first then"); 
    console.log(res); 
    return new Promise(function(resolve,reject){ 
     // reject or resolve 
    }) 
}, function(err){ 
    console.log("first catch"); 
    console.log(err); 
}) 
.catch(function(err){ 
    console.log("second catch"); 
    console.log(err); 
}) 
+0

OP不能檢查'err'的類型嗎? – niceman

+0

@niceman是的,他可以,如果承諾被拒絕,並有特定的錯誤,例如'拒絕(新錯誤(「TESTP_ERROR」))'和'拒絕(新錯誤(「THEN_ERROR」))',可以檢查他們的catch回調中的'err.message'並相應地採取行動。另外,如果你更喜歡定義自己的錯誤來擴展'Error',那麼你可以檢查'if(err instanceof MyCustomError')。注意,一般來說,其他運行時錯誤也可能發生在代碼中,例如調用一個函數在一個未定義的對象上,所以我們必須考慮到那些也會調用'catch'回調函數。 –

+0

通常,你解決這個問題的方式只是區分你正在捕獲的錯誤類型,或者如果你想處理一個特定的錯誤,然後讓鏈從那裏繼續,你在'.then()'後面加上一個'.catch()',這是你想要捕獲的錯誤。 – jfriend00