Await-to-js

await-to-js

Async await wrapper for easy error handling!

Uber tiny module (10LOC) for making life easier while handling error while async-await.

This module is influenced by GoLang style of handling errors:

1
2
data, err := db.Query("SELECT ...")  
if err != nil { return err }  

We would basically covert the below code:

1
2
3
4
5
6
7
8
9
const asyncTask = async () => {
  try {
    const answer = await Promise.resolve(42);
    // any async task.
  } catch(err) {
    // Handle error.
  }
  return answer;
}

to:

1
2
3
4
5
6
7
8
const to = require("await-to-js").default;

const asyncTask = async () => {
  [ err, result ] = await to(Promise.resolve(42));
  if (!err) retrun result;
}

const answer = await asyncTask();

Get it: npm install --save await-to-json

GIF FTW!

await-to-js

Suggest a module

Comments