承诺:忽略捕获并 Return 链
Promise: Ignore Catch and Return to Chain
是否可以忽略捕获并 return 返回链?
promiseA() // <-- fails with 'missing' reason
.then(promiseB) // <-- these are not going to run
.then(promiseC)
.catch(function(error, ignore){
if(error.type == 'missing'){
ignore() // <-- ignore the catch and run promiseB and promiseC
}
})
这样的事情可能吗?
如果您只需要忽略 promiseA 中的所有错误,您可以这样做:
promiseA()
.catch(function(error){
//just do nothing, returns promise resolved with undefined
})
.then(promiseB)
.then(promiseC)
如果您需要 运行 仅在 error.type == 'missing'
时 promiseB,您可以这样做:
promiseA()
.catch(function(error, ignore){
if(error.type == 'missing'){
return promiseB.then(promiseC)
}
})
这是同步类比:
try {
action1(); // throws
action2(); // skipped
action3(); // skipped
} catch (e) {
// can't resume
}
对
try {
action1(); // throws
} catch (e) {
handleError(e);
}
action2(); // executes normally
action3();
这是承诺版本:
asyncActionA() // <-- fails with 'missing' reason
.catch(error => {
if(error.type == 'missing'){
return; // Makes sure the promise is resolved, so the chain continues
}
throw error; // Otherwise, rethrow to keep the Promise rejected
})
.asyncActionB(promiseB) // <-- runs
.asyncActionC(promiseC)
.catch(err => {
// Handle errors which are not of type 'missing'.
});
是否可以忽略捕获并 return 返回链?
promiseA() // <-- fails with 'missing' reason
.then(promiseB) // <-- these are not going to run
.then(promiseC)
.catch(function(error, ignore){
if(error.type == 'missing'){
ignore() // <-- ignore the catch and run promiseB and promiseC
}
})
这样的事情可能吗?
如果您只需要忽略 promiseA 中的所有错误,您可以这样做:
promiseA()
.catch(function(error){
//just do nothing, returns promise resolved with undefined
})
.then(promiseB)
.then(promiseC)
如果您需要 运行 仅在 error.type == 'missing'
时 promiseB,您可以这样做:
promiseA()
.catch(function(error, ignore){
if(error.type == 'missing'){
return promiseB.then(promiseC)
}
})
这是同步类比:
try {
action1(); // throws
action2(); // skipped
action3(); // skipped
} catch (e) {
// can't resume
}
对
try {
action1(); // throws
} catch (e) {
handleError(e);
}
action2(); // executes normally
action3();
这是承诺版本:
asyncActionA() // <-- fails with 'missing' reason
.catch(error => {
if(error.type == 'missing'){
return; // Makes sure the promise is resolved, so the chain continues
}
throw error; // Otherwise, rethrow to keep the Promise rejected
})
.asyncActionB(promiseB) // <-- runs
.asyncActionC(promiseC)
.catch(err => {
// Handle errors which are not of type 'missing'.
});