Try out async/await with Node v7.6.0

If your following closely with node releases you may know Official release of node version 7.6.0 announced on 21–2–2017 , below is list of notable change in node 7.6.0

If you are not familiar with what is promise object and how to use it then read from this Mozilla link,

node v7.6.0 notable changes

The biggest change among all in v7.6.0 is upadtion of javascript V8 engine to version 5.5.

lets look what is new in V8 version 5.5 that will come in latest node release.

Below is V8 version 5.5 notable change list from official V8 website,

V8 version 5.5 release note and new changes

As you can see the biggest change in V8 5.5 is async/await functions.

Now lets have brief introduction to async/await function that is come with latest node version

aync/await are basically ES7 (ES2017 )feature which is currently in draft state for ECMA-262 standard (commonly referred to as JavaScript)

The async function declaration defines an asynchronous function, which returns an AsyncFunctionobject.

The await operator is used to wait for a Promise returned by an async function.

so basically async/await function is cleaner and more readable way to resolve promises than .than() function.

lets try async/await in node version 7.6.0

var request = require('request');
async function getFirstComment() {
try {
let comments = await getComments();
console.log(comments[0]);
} catch (err) {
return err;
}
}
function getComments(){
return new Promise(function(resolve, reject) {
request(' http://localhost:3000/comments',function(error, response, body){
resolve(JSON.parse(body));
})
});
}
getFirstComment();

here, I have function called getFirstComment() which will give me first comment from blog.this function calls getComments() to get all the comments and then returns first comment using http which will be done asynchronously.

now, async keyword outside getFirstComment() tell js engine that this function is can not be executed Asynchronously, and await keyword before getComments() function wait for promise to resolve before further code execution.

when we run this out put window will be,

output window.

now, what if we have multiple promises to resolve

lets take other example where multiple promise will be resolved using async/await.

Multiple promise to be resolve.

Output will be,

output multiple promise.

So As you can see, you can now use async/await in latest version of node that is 7.6.0

Try out and have happy coding!