await-to-js

Async await wrapper for easy error handling without try-catch

Github stars Tracking Chart

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';
// If you use CommonJS (i.e NodeJS environment), it should be:
// const to = require('await-to-js').default;

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);
}

async function asyncFunctionWithThrow() {
  const [err, user] = await to(UserModel.findById(1));
  if (!user) throw new Error('User not found');
  
}

TypeScript 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

Main metrics

Overview
Name With Ownerscopsy/await-to-js
Primary LanguageTypeScript
Program languageJavaScript (Language Count: 2)
Platform
License:MIT License
所有者活动
Created At2016-12-19 20:42:45
Pushed At2024-02-07 06:14:12
Last Commit At2022-05-29 12:06:19
Release Count0
用户参与
Stargazers Count3.3k
Watchers Count21
Fork Count154
Commits Count43
Has Issues Enabled
Issues Count38
Issue Open Count7
Pull Requests Count9
Pull Requests Open Count5
Pull Requests Close Count6
项目设置
Has Wiki Enabled
Is Archived
Is Fork
Is Locked
Is Mirror
Is Private