javascript - 使用 then-catch 的 try-catch 中的 Node.js 问题
问题描述
我写了一个 try-catch 函数,在 try 中,我执行然后 catch 承诺。我想把错误扔给try-catch,catch。我不知道该怎么解释。请查看我的代码,您将在这里理解问题:
try {
function().then(result =>{
if(result){
// do something
function2().then(result =>{
if(result){
// do something
}else{
throw "bad request";
}
}).catch((error)=>{
throw error
})
}else{
throw "not found";
}
}).catch(error =>{
throw error
});
}catch (error){
callback(BAD_REQUEST);
}
我可以这样做还是不这样做,还是有其他方法可以做到这一点?
解决方案
.then
接收回调函数。要捕获错误,您必须将 try-catch 放入 .then 回调中。
该怎么办?
要捕获 Promise 的错误,您可以使用.catch()
或使用现代 async/await。
推荐阅读
- mysql - 数据库错误 PDOException 错误:SQLSTATE[HY000] [1045]
- android - 如何将应用程序安装到 Android 模拟器的 SD 卡而不是其内部存储器?
- javascript - 如何在Javascript上为计时器制作暂停/播放按钮?
- mysql - 在插入错误语法#1064 后选择 count(*) 并选择 sum(my_data)
- python - 如何使用多处理添加大量 pandas df
- c# - 无法使用 WorkItemTrackingHttpClient 更新 WorkItem 状态
- python - Python双重列表到文本文件
- rabbitmq - RabbitMQ Pika - 如何检查消费者是否处于活动状态
- c# - 使用格式说明符货币 C# 的有效方法
- jquery - 添加“包装器” div 标签来包装其他 html div 标签?