visit
— To run ES7 on Node.js, read: BBB, Babel Burger Boilerplate
Before ES5 time, JavaScripters were living in a Callback Hell. Debugging was a crazy console.log-ing job, asphyxia by thousand of callback functions. In later time, Promises came to rescue us, its Magic turns the Hell into a flat structure, a light at the end of the tunnel. Today, Async Await is the incarnation of the Promise. ES7.
Chronological Picture
Who has known that AsyncFunction and Promise siblings? If no you can are not permitted to skip, because this is the reason why await is supported by ES6’s Promise functions and how the characteristic of Promise is applied by Async await, such as Resolving Parallel and Error Handling:
function(){...return new Promise(function(resolve, reject) {...})...}
Example (Thanks for ’s suggestion):
(async function() {
The **async function**
declaration defines an async function, which returns a [AsyncFunction](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction "The AsyncFunction constructor creates a new async function object. In JavaScript every async function is actually a AsyncFunction object.")
object (also a promise). When the async function returns a value, the promise will be resolved with the returned value. When the async function throws an exception or some value, the promise will be rejected with the thrown value ().
Example:
Example:
Example:
Example:
// iterator of objects// for (let thing of things) {
Fellow JavaScripters, it’s time to admit it: we have a problem with promises ().
I really agree with ’s quote_._ Dynamical Promise Array is demanded when dealing with unknown process, dynamical problem. To the issue, my instinct was to push all the Promise functions into an Array, then await each of them sequentially. But it was proved incorrect when I discovered that the Promise functions executed while they were being declared. My conclusion is, don’t trust human instinct when solving problems with Promises.
The walk-around is to store parameters and promises separately (map object is used here)Example:
Errors are swallowed “silently” within an
async
function – just like inside normal Promises ().
Error handling in both Async and Promises were born from the same mother, they both needed try/catch, so that errors are captured and handled in awaited promises from within the async function.
Example:
_try {_ var result1 = await sleep(1);var result2 = await errorSleep(4);var result3 = await sleep(1);
console.log('result1: ', result1)console.log('result2: ', result2)console.log('result3: ', result3)_} catch (err) {_ console.log('err: ', err)console.log('result1: ', result1)console.log('result2: ', result2)console.log('result3: ', result3)}
Like this story? It is helpful to others? It helps me know if you’d like to see write more about his topic and helps people see the story, when tap the heart below.