Node js is a cross-platform and open-source framework and provides n number of useful JavaScript modules that enhances the coding experience and makes web applications development simpler. A few key concepts that are listed in node js interview questions on our website can give you a good insight of all you need to prepare for interviews on node js. It is easy to install, learn, and practice.
In real-life applications, a lot of nested callback functions are needed. Each asynchronous call can then become a pain and lead to confusions. Using async/await simplifies the process of writing nested promises that would otherwise be confusing. It creates a non-blocking code. To make a function async, we need to add the keyword async to the function definition, so that the function returns an async object.
async function sum (a, b){
return a+b;
}
To know how to use async/await, we first need to understand how to write code using promises. We have discussed with command in detail in our node js interview questions and answers section.
Let us go through the steps to use async-await with a promise.
You have to install async with npm install async
command.
Call or import the async in the file where you want to use async.
var async = require("async");
Step3. Make an async function and call await function inside async function.
let phoneChecker = async function (req, res){
const result = await phoneExistOrNot();
}
exports.phoneChecker = phoneChecker;
Await will work only under async function.
Now you can write your business logic in await function.
let phoneExistOrNot = async function (req, res){
return new Promise(function(resolve, reject) {
db.query('select name, phone from users where phone = 123456789 ', function (error, result) {
if(error) {
reject(error);
console.log('Error');
} else {
resolve(result);
console.log('Success');
}
})
});
}
Though just using promise serves the purpose, imagine having more and more nesting – the code would break all the coding standards and at some point, be beyond comprehension. Our collection of advanced node js interview questions explains this point in a more detailed manner.
This is why we need async/await – to eliminate the wrong output issue as well as make our code more straightforward and more robust.
It depends on a developer whether to choose promise or async/await in their code. However, all async functions implicitly return a promise, and every function that returns a promise is an async function. Using a combination of promise and async/await, you can get the benefits of both.