Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Convert an Existing Callback to a Promise in Node.js ?
Next article icon

How to convert function call with two callbacks promise in Node.js ?

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

https://media.geeksforgeeks.org/wp-content/uploads/20240723181053/ezgifcom-gif-to-mp4-converter-(18).mp4




Next Article
How to Convert an Existing Callback to a Promise in Node.js ?
author
devaadi
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-fs-module
  • NodeJS-Questions

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 Dynamically Call Router Function in Node.js ?
    In Node.js Dynamically calling a router function means that the function is selected at runtime based on the request parameters, instead of being explicitly defined in the code. This can be useful when you want to handle a large number of similar requests without having to define a separate function
    4 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
  • How to operate callback-based fs.rename() method with promises in Node.js ?
    The fs.rename() method is defined in the File System module of Node.js. The File System module is basically to interact with hard-disk of the user’s computer. The rename() method is used to rename the file at the given old path to a given new path. If the new path file already exists, it will be ove
    5 min read
  • How to Return an Array from Async Function in Node.js ?
    Asynchronous programming in Node.js is fundamental for handling operations like network requests, file I/O, and database queries without blocking the main thread. One common requirement is to perform multiple asynchronous operations and return their results as an array. This article explores how to
    4 min read
  • How to operate callback based fs.writeFile() method with promises in Node.js ?
    The fs.writeFile() is a 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 fs.writeFile() method asynchronously writes data to a file, replacing the file if it already exists. The fs.writeFile() method i
    5 min read
  • How to operate callback-based fs.readFile() method with promises in Node.js ?
    The fs.readFile() 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 readFile() method is used to asynchronously read the entire contents of a file and returns the buffer form of the data. The fs.read
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences