携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情
- 本文参加了由公众号@若川视野 发起的每周源码共读活动, 点击了解详情一起参与。
- 这是源码共读的第21期
代码确实少,想法确实很有意思
要捕获到await的错误,只能try-catch去捕获,确实是比较恶心的,用这个方式确实方便多了
介绍文章
github:github.com/scopsy/awai…
demo
import to from './to.js';
async function asyncTask() {
let err, user, savedTask;
[err, user] = await to(UserModel.findById(1));
if(!user) throw new CustomerError('No user found');
[err, savedTask] = await to(TaskModel({userId: user.id, name: 'Demo Task'}));
if(err) throw new CustomError('Error occurred while saving task');
if(user.notificationsEnabled) {
const [err] = await to(NotificationService.sendNotification(user.id, 'Task Created'));
if (err) console.error('Just log the error and continue flow');
}
}
显而易见的是,我们来看对比版本,很明显代码少了很多。 当然我们在做网络请求时,返回的一般也不走错误,而是返回正常数据,需要自己做判断辨别。网络错误一般走拦截器,有统一的错误管理。不过大概是我路走窄了。
————原代码
try {
const user = await UserModel.findById(1);
if(!user) return cb('No user found');
} catch(e) {
return cb('Unexpected error occurred');
}
------------变成
let err, user, savedTask, notification;
[ err, user ] = await to(UserModel.findById(1));
if(!user) return cb('No user found');
源码-ts
/**
* @param { Promise } promise
* @param { Object= } errorExt - Additional Information you can pass to the err object
* @return { Promise }
*/
export function to<T, U = Error> (
promise: Promise<T>,
errorExt?: object
): Promise<[U, undefined] | [null, T]> {
return promise
.then<[null, T]>((data: T) => [null, data])
.catch<[U, undefined]>((err: U) => {
if (errorExt) {
const parsedError = Object.assign({}, err, errorExt);
return [parsedError, undefined];
}
return [err, undefined];
});
}
export default to;
js版本
// to.js
export default function to(promise) {
// 去执行本在 await 后的函数,如果正常返回,则返回[null, data]
// 如果报错,返回[err]
return promise.then(data => {
return [null, data];
})
.catch(err => [err]);
}
其他
-
真的很难想象,一个丁点的包,有这么长的package.json,非常值得学习,细节很多