await的异常要用try/catch还是errorFirst?

说是try/catch无法捕获异步函数中的异常,应该用await-to-js的errorFirst的方式,来处理await的异常,大家都是怎么处理await的异常的?

async function asyncTaskWithCb(cb) {
     let err, user, savedTask, notification;
 
     [ err, user ] = await to(UserModel.findById(1));
     if(!user) return cb('No user found');
 
     [ err, savedTask ] = await to(TaskModel({userId: user.id, name: 'Demo Task'}));
     if(err) return cb('Error occurred while saving task');
 
    if(user.notificationsEnabled) {
       [ err ] = await to(NotificationService.sendNotification(user.id, 'Task Created'));
       if(err) return cb('Error while sending notification');
    }
 
    if(savedTask.assignedUser.id !== user.id) {
       [ err, notification ] = await to(NotificationService.sendNotification(savedTask.assignedUser.id, 'Task was created for you'));
       if(err) return cb('Error while sending notification');
    }
 
    cb(null, savedTask);
}
阅读 2.9k
3 个回答

await-to-js 只是封装了一个 try...catch,你也可以自己在异步函数内部用 try...catch 捕获错误,再返回给上一层,跟使用 await-to-js 是一样的。

async function 当然可以用 try...catch... 捕获异常,并且可以将异步操作前后放在同一个调用栈显示,这个特性是 async function 与之前的 Promise 实现最大的不同。

error 和 try catch 都太丑了,我选择 FP 理念中的 Either

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题