Async Await in Node.js

Async Await are the modern tools in node for handling async operations providing better redability to the code. This functions with async keyword automatically returns a promise. The functions need not to be chained one after another, simply await the function that returns the Promise. But the function async needs to be declared before awaiting a function returning a Promise. The code now looks like below. Example: After async/await async function fun1(req, res){ let response = await request.get(‘http://localhost:3000’); if (response.err) { console.log(‘error’);} else { console.log(‘fetched response’); } Define an async function which means use the async keyword before the function definition. This functional implecitly returns a promise. async fun(){ //… } Then use the await keyword before the function returning a promise, it pauses the execution untill the promise is respolved async fun(){ let response = await fetchData(); return response; }

Leave a comment

Your email address will not be published. Required fields are marked *