JSTotD: Why async functions?

Re: Async Functions and await

So the basic reason for introducing such functions are mainly an attempt to reduce the code size, nesting and hence the complexity? Just a better way to organise the code? Because they don’t seem to do anything new.
I saw similar changes in coding methodology in Unity too while scripting with C#. It’s called IEnumerator, which is coupled with yield return. And that reduces the code which is otherwise difficult to read if replaced by event-listeners.

It’s true that they don’t necessarily add anything new. Complexity and organization are the real benefits. And with that, consistency in writing code, particularly in being able to write code that looks like synchronous code despite it being asynchronous, all thanks to the help of a couple of keywords (async and await) that helps us escape the promise API completely (most of the time).

Where this especially becomes helpful is allowing a promise chain to occur all in the same scope, especially as you might have dependencies scattered throughout would-be then() callbacks. For example:

getUser()
    .then(user => {
        return user.getAccount();
    })
    .then(account => {
        // but now how do I access user?
    });
    
// vs

let user = await getUser();
let account = await user.getAccount();
// user and account in scope

If you’ve ever worked with async promise code in ES5, you may know the struggles. The lack of arrow functions in combination with the use of the promise API can make for some messy code (yes, I had a bad experience).