2017-10-20 58 views
0

如果任何下一個方法失敗,是否可以使用從前鏈方法返回的值到catch方法?可能會傳遞一個前一個Promise,然後將值傳遞給一個然後鏈中的catch方法?

因此,舉例來說,如果我們有:

fetch('https://example.com') 
    .then(res => doSomething(res)) 
    .then(res2 => doSomethingElse(res2)) 
    .then(res3 => console.log(res3)) 
    .catch(res2 => console.log(res2)) 

所以說,第二個則失敗(doSomethingElse),我可以通過一次成功的值,那麼到catch塊? (在這種情況下,第一個將是最後一個通過)

+0

使用拼圖就只有你想使用這些承諾處理錯誤,使'res2'仍處於範圍:'取(...)。然後(DoSomething的)。然後(RES2 => doSomethingElse.then( res3 => console.log(res3))。catch(err => console.log(res2,err)))。catch(err2 => ...)' – Bergi

+0

Ahh好主意,謝謝你,對於重複問題感到抱歉。 – Byrd

+0

其實我不太確定它是否是一個很好的重複,因爲控制流實際上在錯誤情況下非常不同 - 只有[嵌套方法](https://stackoverflow.com/a/28250687/1048572)適合這裏。也許我應該重新打開併發布正確答案。 – Bergi

回答

0

爲什麼你不使用這個變量?

var lastResult = null  
fetch('https://example.com') 
    .then(res => lastResult = res; doSomething(res)) 
    .then(res2 => lastResult = res2; doSomethingElse(res2)) 
    .then(res3 => lastResult = res3; console.log(res3)) 
    .catch(err => process(lastResult); console.log(err)) 
+0

是的,我想你可以這樣做,我正在尋找一種適合流程的方式,有點像@Bergi評論以及他連接的問題,因爲我的是重複的。儘管謝謝你的回答! – Byrd

相關問題