- Async/Await allows for a clean and concise codebase with fewer lines of code, less typing, and fewer errors. Ultimately, it makes complicated, nested code readable again.
- Error handling with try/catch (in one place, rather than in every call)
- Error stacks make sense, as opposed to the ambiguous ones that you receive from Promises, which are large and make it difficult to locate where the error originated. Best of all, the error points to the function from which the error came
How It Works
An async function returns a promise, like in this example:
When you want to call this function you prepend
await, and the calling code will stop until the promise is resolved or rejected. One caveat: the client function must be defined as
Here’s an example:
A Detailed Example
This is a simple example of async/await used to run a function asynchronously:
Before After I did something //after 3s
Promise All The Things
async keyword to any function means that the function will return a promise. Even if it’s not doing so explicitly, it will internally make it return a promise.
This is why this code is valid:
and it’s the same as:
The code is much simpler to read.
As you can see in the example above, our code looks very simple. Compare it to code using plain promises, with chaining and callback functions. And this is a very simple example, the major benefits will arise when the code is much more complex.
For example here’s how you would get a JSON resource, and parse it, using promises:
And here is the same functionality provided using await/async:
Multiple async Functions in Series
Async functions can be chained very easily, and the syntax is much more readable than with plain promises:
I did something and I watched and I watched as well
Debugging promises is hard because the debugger will not step over the asynchronous code. Async/await makes this very easy because to the compiler it’s just like synchronous code.