Async await wrapper for easy error handling
You need ES7 transpiler in order to use async/await functionality. You can use babel or typescript for that.
npm i await-to-js --save
import {init} from 'await-to-js';
// this is the same 'to' function but with given interceptor
const to = init((err, data) => {
// use err and data
});
import to from 'await-to-js';
async function asyncTask(cb) {
const [ err, user ] = await to(UserModel.findById(1));
if(!user) return cb('No user found');
const [ err, savedTask ] = await to(TaskModel({userId: user.id, name: 'Demo Task'}));
if(err) return cb('Error occurred while saving task');
if(user.notificationsEnabled) {
const [ err ] = await to(NotificationService.sendNotification(user.id, 'Task Created'));
if(err) return cb('Error while sending notification');
}
if(savedTask.assignedUser.id !== user.id) {
const [ 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);
}
MIT © Dima Grossman && Tomer Barnea