[Javascript] ES7 Async Await BIBLE

7,102 reads

8 must know Examples :

AsyncFunction Object Promise function Async function Await Sequentially Await Parallelly Await Nest Await Dynamically Error Handle

Note

— 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

1- Constructor of async: asyncFunction

The AsyncFunction constructor creates a new Async function object. In JavaScript every Async function is actually a AsyncFunction object. From Mozilla:

//Node.js

console.log(async function () {});

// Chrome or Firefox

console.log(async function () {}.constructor);

console.log(async function () {}.__proto__);

(Thank you for Albin Larsson for the correction)

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) {

...

})

...

}

2- Constructing Promise function

Why are we talking about Promise functions here? Because people may have missed that the foundation of Async await are promises, every Async function we create and every thing that we Await will naturally become a promise.

Example (Thanks for Jyotman Sing’s suggestion):

(async function() {

var sleep = function(para) {

return new Promise(function(resolve, reject) {

setTimeout(function() {

resolve(para * para)

}, 1000)

})

}

var result = await sleep(2)

// result is 4

})();

3- Constructing Async function

The async function declaration defines an async function, which returns a AsyncFunction 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 (Mozilla).

Example:

async function asyncSleep (para){

return await sleep(para)

}

var result = await asyncSleep(2)

//result is 4

asyncSleep(3).then(function(result2){

//result2 is 9

})

4- Await Sequentially

Example:

var result1 = await sleep(2);

var result2 = await sleep(result1);

var result3 = await sleep(result2);

//result1 is 4

//result2 is 16

//result3 is 256

5- Await Parallelly

Example:

var results = await Promise.all([sleep(1), sleep(2)]);

//results is [1,4]

6- Nest

Example:

// iterator of objects

// for (let thing of things) {

for(var i =0 ; i<3; i++){

var result = await sleep(i);

for(var j =0 ; j<result; j++){

console.log(' i:'+i+', j:'+j+': ', await sleep(j));

}

}

// i:1, j:0: 0

// i:2, j:0: 0

// i:2, j:1: 1

// i:2, j:2: 4

// i:2, j:3: 9

7- Dynamic Async functions

Fellow JavaScripters, it’s time to admit it: we have a problem with promises (Nolan Lawson).

I really agree with Nolan Lawson’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:

var sleep = function(para1,para2) {

var _para1 = para1, _para2 = para2 || para1 ;

return new Promise(function(resolve, reject) {

setTimeout(function() {

resolve(_para1 * _para2)

}, 1000)

})

}

var proMap = new Map();

proMap.set([1], sleep);

proMap.set([2, 3], sleep);

proMap.set([3], sleep);

for (var [para, fun] of proMap.entries()) {

var result = await fun.apply(this, para);

console.log(para, result)

}

//[ 1 ] 1

//[ 2, 3 ] 6

//[ 3 ] 9

8- Error handle

Errors are swallowed “silently” within an async function – just like inside normal Promises (Nicolas Bevacqua).

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:

var errorSleep = function(para) {

return new Promise(function(resolve, reject) {

setTimeout(function() {

reject(' ErrorSleep')

}, 1000)

})

}

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)

}

//err: ErrorSleep

//result1: 1

//result2: undefined

//result3: undefined

Summary:

Good, async/await is a great syntactic improvement for both nodejs and browser programer. Comparing to Promises, it is a shortcut to reach the same destination. It helps developer to implement functional programming in JavaScript, and increases the code readability, making JavaScript more enjoyable.

Bad, as mentioned in part 7 and 8, Promise has problem in generating instance dynamically and resolving the instance, also await should have given Javascripter a louder shout when an accident exception is found.

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.

Reference:

Mozilla:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction

Nicolás Bevacqua

https://ponyfoo.com/articles/understanding-javascript-async-await

Nolan Lawson

https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

Tags