Skip to content

A JavaScript async-await wrapper for easy error handling like Golang (without try-catch).

License

Notifications You must be signed in to change notification settings

RexSkz/await-to-go

 
 

Repository files navigation

await-to-go

NPM version Downloads

Async await wrapper for easy error handling like Golang

Special thanks to https://github.com/scopsy/await-to-js for the inspiration, actually I forked this project and make some small changes.

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-go --save

Usage

import go from 'await-to-go';
// If you use CommonJS (i.e NodeJS environment), it should be:
// const go = require('await-to-go').default;

async function asyncTaskWithCb(cb) {
  let err, user, savedTask, notification;

  // data and error are returned
  [user, err] = await go(UserModel.findById(1));
  // handling error here, not data itself
  if (err) return cb('No user found');

  [savedTask, err] = await go(TaskModel({userId: user.id, name: 'Demo Task'}));
  if (err) return cb('Error occurred while saving task');

  if(user.notificationsEnabled) {
    [, err] = await go(NotificationService.sendNotification(user.id, 'Task Created'));
    if (err) return cb('Error while sending notification');
  }

  if(savedTask.assignedUser.id !== user.id) {
    [notification, err] = await go(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 [user, err] = await go(UserModel.findById(1));
  if (err) throw new Error(err);
}

TypeScript usage

interface ServerResponse {
  test: number;
}

const p = Promise.resolve({test: 123});

const [data, err] = await go<ServerResponse>(p);
console.log(data.test);

License

MIT

About

A JavaScript async-await wrapper for easy error handling like Golang (without try-catch).

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 76.6%
  • JavaScript 23.4%