javascript - 如果你在一个promise中有一个promise,你需要两个catch吗?
问题描述
例如,使用fetch()
(.then() 中的第二个)进行两次调用,您需要两个.catch()
还是只需要外部一个就足够了?
我试图复制,但到目前为止还不能。
b = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Solving...');
resolve('solved');
}, 3000);
})
.then(() => {
new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Rejecting...');
reject('error');
}, 1000);
})
.then(() => null)
.catch((error) => {
console.log('Catching error inside.');
console.log(error);
});
})
.catch((error) => {
console.log('Catching error outside.');
console.log(error);
});
这有效,但如果我删除内部catch()
我会得到Unhandled promise rejection
错误
Solving...
Rejecting...
(node:73650) UnhandledPromiseRejectionWarning: error
(node:73650) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:73650) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
解决方案
无需多次 catch()。如果检测到任何错误,则转到 catch()
推荐阅读
- android - 如何在 kotlin android 中比较日期和时间?
- r - R中的Aregexec没有提取它应该找到的字符串
- selenium - 无法访问 mat-icon 可见或不使用 selenium
- c# - 更改 GridView 中 ItemTemplate 内的 ImageButton 图像源
- mysql - 尝试使用 Mysql 安装程序自定义安装 mysql 工作台和服务器,但“可用产品”下的列表对我来说完全是空的?
- javascript - 如果它是计算器上的数学符号,我如何删除最后一个输入
- php - file_get_contents 无法打开流:无法分配请求的地址
- json - API JSON 到 CSV 或 Google 表格
- powerbi - DAX - 查找并返回具有最高汇总度量的类别值
- content-security-policy - 启用头盔时如何在 nodejs 应用程序中使用 3rd 方库和内联脚本