paint-brush
Asycn Await BIBLE: Sequential, Parallel, Nest, Dynamic and Error Handle in Javascriptby@peterchang_82818
8,923 reads
8,923 reads

Asycn Await BIBLE: Sequential, Parallel, Nest, Dynamic and Error Handle in Javascript

by December 10th, 2016
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<em>— This story only focuses on Asynchronies issue.<br> — To Nodejs developer, to run ES7 please read: </em><a href="https://hackernoon.com/nodejs-bbb-babel-burger-boilerplate-b74107eff049#.5x9fvu8ji" target="_blank">BBB, Babel Burger Boilerplat</a>e

People Mentioned

Mention Thumbnail

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Asycn Await BIBLE: Sequential, Parallel, Nest, Dynamic and Error Handle in Javascript
 HackerNoon profile picture

Before ES5, JavaScripters were living in a Callback Hell. Debugging was a crazy console.log-ing inside thousand of callback functions. Then Promises came to rescue JavaScripters. The Magic of Promises turned that Hell into a flat structure, and it was the light at the end of the tunnel. Async Await was the incarnation of the Promise. ES7.

8 must know Examples :

  1. AsyncFunction Object
  2. Promise function
  3. Async function
  4. Await Sequentially
  5. Await Parallelly
  6. Await Nest
  7. Await Dynamically
  8. Error Handle

Note


— This story only focuses on Asynchronies issue. — To Nodejs developer, to run ES7 please read: BBB, Babel Burger Boilerplate

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:

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

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](https://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 (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:


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:


Source:https://medium.com/@peterchang_82818/javascript-es7-async-await-bible-tutorial-example-32294f6133ab#.m33vwg1yx


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


Nicolás Bevacquahttps://ponyfoo.com/articles/understanding-javascript-async-await


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