Javascript 承诺从“然后”内部调用“捕获”`
有没有一种方法可以从then回调直接跳转到JavaScript承诺“then chain”中的catch回调 因此,通过示例,我正在检查一个提取调用中的数据:Javascript 承诺从“然后”内部调用“捕获”`,javascript,asynchronous,es6-promise,Javascript,Asynchronous,Es6 Promise,有没有一种方法可以从then回调直接跳转到JavaScript承诺“then chain”中的catch回调 因此,通过示例,我正在检查一个提取调用中的数据: fetch('api') .then(response => { if (response.json() === null) { // error // call catch } else { return response.json();
fetch('api')
.then(response => {
if (response.json() === null) {
// error
// call catch
}
else {
return response.json();
}
})
.then(data => console.log(data.message))
.catch(error => console.log(error));
有什么最佳实践或解决方法吗?您可以在第一个
中抛出一个错误。然后
promise.then(response => {
if (response.json() === null) {
// error
// call catch
throw new Error('error !');
}
else {
return response.json();
}
})
.then(data => console.log(data.message))
.catch(error => console.log(error)); // error !
您可以调用带有错误的Promise.reject
。您将在catch()
方法中收到错误
fetch('api')
.then(response => {
if (response.json() === null) {
return Promise.reject('Somethind bad happened');
}
else {
return response.json();
}
})
.then(data => console.log(data.message))
.catch(error => console.log(error));
你不会“呼叫捕获”,你会抛出一个错误。你不会抛出一个异常,你会返回一个被拒绝的承诺。