A better async/await approach

Photo by Suganth on Unsplash

When to use await

(async () => {
// we can await any value or callback
const regular = () => 'regular';
// but we don't need to await returned promises
const promise = () => Promise.resolve('promise');
// we also should use `async` *only*
// if we need to `await` something
const asynchronous = async () => {
await regular();
// we don't need to await promise()
// we can return *just* promise()
return promise();
};
// let's test them all
console.log(await regular());
console.log(await promise());
console.log(await asynchronous());
})();
const getData = async endPoint => {
const response = await fetch(endPoint);
return response.json(); // awesome 🎉
};
const getData = async endPoint => {
const response = await fetch(endPoint);
return await response.json(); // WHY ??? 😩
};

1. Performance

const rand = async () => Promise.resolve(Math.random());
const arand = async () => await Promise.resolve(Math.random());
const randBench = async () => {
const randos = [];
console.time('rand');
for (let i = 0; i < 0xFFFF; i++)
randos.push(await rand());
console.timeEnd('rand');
return randos;
};
const arandBench = async () => {
const randos = [];
console.time('arand');
for (let i = 0; i < 0xFFFF; i++)
randos.push(await arand());
console.timeEnd('arand');
return randos;
};
randBench();
rand: 256.119873046875 ms
arandBench();
arand: 600.880859375 ms

2. Logic

const getData = async endPoint => {
try {
const response = await fetch(endPoint);
return await response.json();
}
catch (error) {
console.error(error);
return {};
}
};

Trying a better approach

const debug = async (callback, ...args) => {
try {
return await callback(...args);
}
catch (cought) {
const error = new Error(
callback.name || String(callback)
);
error.stack += '\n' + cought.stack;
throw error;
}
};
const data = await debug(getData, endPoint);
const debug = process.env.PRODUCTION ?
(callback, ...args) => callback(...args) :
() => { /* ... previous code ... */ };

Conclusion

… but, it’s explicit!

const whatever = async value => await value;
await whatever('nope'); // works
await whatever(false); // works too
await whatever(Promise.resolve('maybe'));
// also works

In a gist

Web, Mobile, IoT, and all JS things since 00's. Formerly JS engineer at @nokia, @facebook, @twitter.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store