如果下一个方法中的任何一个失败,是否可以使用从上一个然后方法返回的值在然后链中到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 块吗?(在这种情况下,第一个将是最后一个通过)
为什么不为此使用变量?
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) )