node package manager
Love JavaScript? Your insights can make it even better. Take the 2017 JavaScript Ecosystem Survey »

await-to-js

await-to-js

NPM version Downloads

Async await wrapper for easy error handling

Pre-requisites

You need to use Node 7.6 (or later) or an ES7 transpiler in order to use async/await functionality. You can use babel or typescript for that.

Install

npm i await-to-js --save

Usage

import to from 'await-to-js';
 
async function asyncTask(cb) {
     let err, user, savedUser, 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);
}

Type script usage

interface ServerResponse {
  test: number;
}
 
const p = Promise.resolve({test: 123});
 
const [err, data] = await to<ServerResponse>(p);
console.log(data.test);

License

MIT © Dima Grossman && Tomer Barnea