How to Rewrite promise-based applications to Async/Await in Node.js ?
Last Updated :
25 Jul, 2024
In this article, we are going to see how we can rewrite the promise-based Node.js application to Async/Await.
Suppose we have to read the content of a file 'index.txt', and we have a function 'readFilePromise' which uses the 'readFile' method of the fs module to read the data of a file, and the'readFilePromise' function resolves the promise if the data is found otherwise rejects the promise with respective error.
const fs = require('fs');
const readFilePromise = (fileName, encoding) => {
return new Promise((resolve, reject) => {
fs.readFile(fileName, encoding, (err, data) => {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
then, we can handle data by calling the 'readFilePromise' function with two arguments, the file path, and the file encoding, if it gets the required output then it executes the code of then block, and if it gets the error then it executes the code of the catch block.
readFilePromise('./input.txt', 'utf8')
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
Example:
JavaScript
const fs = require('fs');
const readFilePromise = (fileName, encoding) => {
return new Promise((resolve, reject) => {
fs.readFile(fileName, encoding, (err, data) => {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
readFilePromise('./input.txt', 'utf8')
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
Output:
Now let's rewrite this promise to async/await. For using 'await', we have to use the 'async' keyword, 'await' to hold the execution of the program till the 'readFile' method of the fs module returns something. It can be an error or required data, if it is an error then we have to log the error, if not then log the required data.
const fs = require('fs');
const readFileAsyncAwait = async (filePath, encoding) => {
await fs.readFile(filePath, encoding, (err, data)=>{
if(err){
console.log(err);
}
console.log(data);
});
}
Then we can call the 'readFilePromise' function with two arguments, the file path, and the file encoding, and if there is any error, it simply logs the error otherwise log the required data.
readFileAsyncAwait('input.txt', 'utf8');
Example:
JavaScript
const fs = require('fs');
const readFileAsyncAwait = async (filePath, encoding) => {
await fs.readFile(filePath, encoding, (err, data)=>{
if(err){
console.log(err);
}
console.log(data);
});
}
readFileAsyncAwait('input.txt', 'utf8');
Output:
Similar Reads
Explain Async Await with Promises in Node.js Async/Await in Node.js is a powerful way to handle asynchronous operations. It allows you to write asynchronous code in a synchronous manner, making it easier to read, write, and debug. This feature is built on top of Promises, which represent a value that may be available now, or in the future, or
4 min read
How to use Async-Await pattern in example in Node.js ? Modern javascript brings with it the async-await feature which enables developers to write asynchronous code in a way that looks and feels synchronous. This helps to remove many of the problems with nesting that promises have, and as a bonus can make asynchronous code much easier to read and write.
1 min read
How to Convert an Existing Callback to a Promise in Node.js ? Node.js, by nature, uses an asynchronous, non-blocking I/O model, which often involves the use of callbacks. While callbacks are effective, they can lead to complex and hard-to-read code, especially in cases of nested callbacks, commonly known as "callback hell." Promises provide a cleaner, more rea
7 min read
How to use Async/Await with a Promise in TypeScript ? In TypeScript, you can use async and await with a Promise to simplify asynchronous code and make it more readable.What is a Promise?A promise in TypeScript is an object representing the eventual completion or failure of an asynchronous operation. It acts as a placeholder for a value that may be avai
3 min read
How to delay a loop in JavaScript using async/await with Promise ? In JavaScript, you can delay a loop by using async/await with Promise. By wrapping a setTimeout() inside a Promise and using await, you can pause execution at each iteration, creating delays between loop iterations for asynchronous tasks without blocking the main thread.What is async and await?async
2 min read
How to Push Data to Array Asynchronously & Save It in Node.js ? Node.js is a powerful environment for building scalable and efficient applications, and handling asynchronous operations is a key part of its design. A common requirement is to collect data asynchronously and store it in an array, followed by saving this data persistently, for instance, in a databas
7 min read