The Definitive Guide to the ES7 Async Functions
Most JavaScript code that relies on asynchronous data is written using continuation-passing style, e.g.
There are a few things that can help to minimize the so-called callback hell (viz., using named functions over anonymous functions, modularization). Nonetheless, sequential iterations remains a PITA.
We can use ES6 Promise to perform sequential iteration.
If you are comfortable working with ES6 Promise, ES7 async/await is the sugar-coated equivalent.
await keyword expects ES6 Promise:
- If/when promise is resolved, the return value is the resolved value.
- If/when promise is resolved, the error thrown is what been used to reject the promise.
You can use await only in async function.
await* is a syntactic sugar for Promise.all.
Async Functions for ECMAScript proposal was accepted into stage 1 ("Proposal") of the ECMASCript 7 spec process in January 2014. The spec text can be found here.
You can run async/await code using a transpiler (source-to-source compiler). Babel transpiler has the biggest coverage of ES6 and ES7 features.
npm install babel@5.0.4 -g
babel-node --stage 1 ./your-script.jsasync/await makes the biggest difference when you have multiple dependencies that need to be fetched asynchronously, e.g. (the requirement is to have all three connections open at once)
Of course, even the latter can be flattened using Bluebird .spread().
Nonetheless, I prefer await keyword.
You must wrap all instances of await in a try...catch statement.
The promise that we await for is rejected. Rejection terminates the async block but does not propagate to the program. The output of the above program:
a
1
b
[Error: Oops #0]Take a moment to observe that [Error: Oops #0] comes after b and 1 does not. This is because the async function is defined as IIFE. To delay
As the code base grows it becomes harder and harder to handle errors within async functions.
Remember that beneath the surface, await simply handles ES6 Promise.
You can use Bluebird Promise implementation to take advantage of the global rejection events.
When I started using async/await my first test cases were these:
Remember that beneath the surface, await simply handles ES6 Promise.
You can use your regular testing strategy that you use when testing Promise objects. I use chai-as-promised.
My experience was that using Promise directly for testing has prooved to be more reliable then experimental async/await.