How to convert function call with two callbacks promise in Node.js ?
Last Updated :
23 Jul, 2024
Promise: Promise is used to handle the result, 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.
A promise looks like this -
function()
.then(data => {
// After promise is fulfilled
console.log(data);
})
.catch(err => {
// After promise is rejected
console.error(err);
});
Callback: A callback is the last argument of a function. It will be executed to do something with the values that we get from the function. A function call with two callbacks looks like this
fs.readFile('./hello.txt', ,'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
This is a readFile function of the File System Module. It is used to read the data of a file. readFile function can call with two parameters: File Path, File Encoding, and callbacks. File-path is the path where your file is present & File Encoding is the encoding to that file, by default it is "utf8". Inside callbacks, check for the error, if error then logs the error, if no then log the result.
Let's run this function first: Make sure that you have created a file "hello.txt" with some content on it in this case it is 'Hello World'.
Example:
JavaScript
const fs = require('fs');
fs.readFile('./hello.txt', ,'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
Output:
let's convert this into a promise.
Mechanism: For converting this readFile function into a promise, we have to make a new function let's call it readFilePromise with two arguments fileName & encoding. Inside this function, we return a new promise, and this promise uses the readFile function inside it. If the readFile function returns the required output then it resolves the promise, which means it returns the data as a promise, and if the function doesn't return the required output then it rejects the promise which means it returns an error instead of data.
const readFile = (fileName, encoding) => {
return new Promise((resolve, reject) => {
fs.readFile(fileName, encoding, (err, data) => {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
Complete Code:
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('./hello.txt', 'uft8')
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
Step to run the application: Open the terminal and type the following command.
node app.js
Output:
Similar Reads
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 Convert Callback to Promise in JavaScript ? Asynchronous programming in JavaScript often involves the use of callbacks. However, callbacks can lead to callback hell and make the code harder to read and maintain. Promises provide a cleaner way to handle asynchronous operations. Converting existing callback-based code to use promises can improv
2 min read
How to convert an asynchronous function to return a promise in JavaScript ? In this article, we will learn how to convert an asynchronous function to return a promise in JavaScript. Approach:Â You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need
3 min read
How to operate callback-based fs.truncate() method with promises in Node.js ? The fs.truncate() method defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the userâs computer. The truncate() method is used to modify the inner contents of the file by âlenâ bytes. If len is shorter than the fileâs current length, t
4 min read
How to operate callback-based fs.readdir() method with promises in Node.js ? The fs.readdir() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the userâs computer. The readdir() method is used to read the contents of a directory. The fs.readdir() method is based on callback. Using callback methods l
3 min read