Using Async Await In Nodejs
Posted By : Sakshi Gadia | 12-Feb-2018
Why async/await?
The problem with node js async is some of the task run parallely, by using nested callbacks or execution of multiple asynchronous operations one after another lead to callback hell. The problem of callback hell was resolved by promises but it also created problem with promise chaining, as it return promises again and again. If in a promise chain an error is occured, it return a promise chain which does not gives any clue from where the error is thrown.
async/await
Using async await you are able to write functions which can block each asynchronous operation, it waits until the result is not get. To use async function in your code you can use through Babel.
function getData() {
return new Promise(resolve => {
fs.readFile("data.txt", 'utf8', function(err, data) {
if (err) throw err;
resolve(data);
});
});
}
async function saveData() {
var getData_result = await getData(srcPath)
fs.writeFile('savePath.txt', getData_result, function(err) {
if (err) throw err;
console.log("complete")
});
}
saveData();
As async function is called, it return promise.
In above code our function has a keyword with async before it, await keyword is used inside those function is defined with async. As await is defined inside async function, it pauses the execution of async function and waits for the promise to be resolved. As it get promise value, it resumes the async function execution and return resolved value.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sakshi Gadia
An experienced MEAN Stack developer having good knowledge in Nodejs, MongoDb. Apart from these in my spare time, I enjoy playing chess and ready to learn new technologies.