❤️Please consider starring this project to show your love and support.🙌
About
ES7 async/await gives to developers ability to write asynchronous code that look like synchronous. But under the hood it is still just a sugar on top of the ES6 Promise.
You can write code that looks clean, but only unless you have to catch errors. To catch thrown error or handle the promise's rejection you have to surround it with try-catch block or fallback to pure promises and from that moment visual purity of your code is over.
But there is a solution!☀️
I really like the way it's done in Go. It has no error throwing mechanism, but has a multi-value return and the common way to handle errors in Go is to return error as a last value, like so:
data, err := someErrorFunc(someStuff)
if err != nil {
return err
}
But JavaScript has no multi-value return! - you would say. Sad, but true.
But!
It has a destructuring assignment and await-of gives you ability to do this:
import { of } from "await-of";
async () => {
let [res, err] = await of(axios.get("some.uri/to/get"));
if (err) {
if (!err.response) {
throw err;
}
res = err.response;
}
const { data, status = 0 } = res;
console.log(data, status);
};
There is no modifications needed in function/promise you want to await - just pass it to the of() and whole the magic will be done.
Installation
npm i --save await-of
Usage
import { of } from "await-of";
async function someAsyncStuff() {
let error, data;
[data] = await of(Promise.reject(new Error("ERROR!")));
console.log(data);
[, error] = await of(Promise.reject(new Error("ERROR!")));
console.log(error);
[, error] = await of(
new Promise(() => {
throw new TypeError("ERROR!");
})
);
console.log(error.message);
}
Tests
npm install
npm run test