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