It is basically executing Asynchronous Tasks in series or synchronously. Java is Asynchronous in nature and so is the Node. Node handles multiple requests at the same time by using Event loop and callback functions.
There are 2 methods to perform different asynchronous functions synchronously or sequentially:
Using Callback function: It is the Event handler in the Node. This function is generally called at the completion of a given task.
Reading the files in parallel using callbacks required for a loop. In order to read a file sequentially, it requires a recursive function. This function checks if it has reached the last file. If so, it is completed otherwise it will continue reading the next file.
The code for the following example is as follows:
- The code is to read all the files in the folder in sequence using callbacks.
- To read files in the folder, we will first have to see which files are in the folder.
Example 1: In this example, we will use the callback function.
javascript
const fs = require( "fs" );
fs.readdir( "..." , function (err, files) {
if (err) {
console.log( "Error in file contents." );
}
else {
let ttlBytes = 0;
let readFiles = function (index) {
if (index == files.length) {
console.log( "Done reading all the files. ttlBytes = "
+ ttlBytes);
}
else {
fs.readFile(files[index], function (err, data) {
if (error) {
console.log( "Error reading the file" , err);
} else {
ttlBytes += data.length;
readFiles(index + 1);
}
});
}
};
readFiles(0);
}
});
|
Output:
Error in file contents.
Using Promises: It is a design pattern in Node.js to avoid the callback hell. These are introduced to reduce the complexity of Asynchronous JavaScript code. A promise has 3 states:
- Pending: You don’t know if people will come to your birthday party or not.
- Rejected: If the promise has been rejected it means people have refused to come to your birthday party.
- Resolved: If the promise has been resolved it means people are ready to come to your birthday party.
The code for the following example is as follows:
Example 2: In this example, we will use promises.
javascript
const arePeopleReady = true ;
const invitationBirthday = new Promise((resolve, reject) => {
if (arePeopleReady) {
return resolve( 'People are ready to come to your Birthday party' );
} else {
var reason = new Error( 'People are not Ready' );
return reject(reason);
}
});
const askPeople = () => {
invitationBirthday
.then((fulfilled) => {
console.log(fulfilled);
})
. catch (error => {
console.log(error.message);
});
}
askPeople();
|
Output:
People are ready to come to your Birthday party
Other design methods to avoid callback-hell in Node.js are as follows:
- Execute Tasks In Series Using Async.series.
- Execute tasks In Series Using Async/Await.
- Execute Tasks In Series Using Async.waterfall.
Using Async/Await: An example of Async/Await can be shown as follows:
- Here in this example, we are not using rejections/errors just for the sake of simplicity
- Async functions return a Promise
- If the function shows an error, the Promise will be rejected. If the function returns a value, the Promise will be resolved.
Example 3: In this example, we will use Async/Await.
javascript
const x=2
function addIntAfter4Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x + 4);
}, 2000);
});
}
async function addAsync(x) {
const a = await addIntAfter4Seconds(10);
const b = await addIntAfter4Seconds(20);
const c = await addIntAfter4Seconds(30);
return x + a + b + c;
}
addAsync(x).then((sum) => {
console.log(sum);
});
|
Output:
74
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
31 Mar, 2023
Like Article
Save Article