Promises are an incredibly important part of JavaScript. It allows us to hook into the completion of asynchronous calls, making chained asynchronous operations simple.
But there is a (not so) tiny downside - Promises are not the best solution in terms of prettiest syntax.
The async
and await
keywords are syntactic sugar for Promises. They aid in presenting the asynchronous code in a synchronous way. They introduce no new concepts, but they change the way that Promise-based code is written.
Before/after async/await
Here is some code that uses plain Promises:
const doAsynchronousStuff = ...; // function that returns a Promise
doAsynchronousStuff().then(result1 => {
return doAsynchronousStuff(result1);
}).then(result2 => {
return doAsynchronousStuff(result2);
}).then(result3 => {
return doAsynchronousStuff(result3);
}).catch(e => {
// handle the error
});
Notice the use of callback functions. However, with async/await
this becomes:
try {
const result1 = await doAsynchronousStuff();
const result2 = await doAsynchronousStuff(result1);
const result3 = await doAsynchronousStuff(result2);
} catch (e) {
// handle the error
}
Notice how it looks just like regular, synchronous, non-Promise-based code, except it supports waiting for the Promise to be resolved!
Collapse
Top comments (3)
If you want to compare them in terms of prettiness, the very least you could do is choose a good example of promises, not something that looks ugly for no reason.
To be fair, the async/await example could easily be extended to include additional transformation on the values resolved from each Promise; however, that no longer is possible with this type of shortening. For example:
^ This is only possible in a callback-based Promise syntax when expanded callbacks are used.
Sure you can!
To be entirely fair, both syntaxes can be expanded to become more complex than this simple example and both can be used to write ridiculously awkward code. My sole point is that in order to compare different things, you should strive to use the best of both groups, rather than making up examples that suit your point.