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 asynchronous function to return a promise in JavaScript ?
Next article icon

How to Convert an Existing Callback to a Promise in Node.js ?

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

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 readable way to handle asynchronous operations. This article will guide you through the process of converting existing callbacks to promises in Node.js.

Table of Content

  • Why Convert Callbacks to Promises?
  • Structure of a Callback
  • Converting Callbacks to Promises
    • Wrap the Function in a Promise:
    • Error Handling:
    • Chaining Promises:

Why Convert Callbacks to Promises?

  • Readability: Promises make code easier to read and maintain by avoiding deep nesting.
  • Error Handling: Promises provide a unified approach for error handling using .catch() blocks.
  • Chaining: Promises support chaining, allowing sequential asynchronous operations to be handled more gracefully.
  • Compatibility: Modern JavaScript features like async/await work seamlessly with promises, making asynchronous code even more readable and manageable.

Structure of a Callback

Here, fs.readFile is an asynchronous function that takes a file path, an encoding, and a callback function that is executed once the file has been read.

const fs = require('fs');  fs.readFile('example.txt', 'utf8', (err, data) => {     if (err) {         console.error('Error reading file:', err);         return;     }     console.log('File content:', data); });

Approach

Installation Steps

Step 1: Make a folder structure for the project.

mkdir myapp

Step 2: Navigate to the project directory

cd myapp

Step 3: Initialize the NodeJs project inside the myapp folder.

npm init -y

Project Structure:

Screenshot-2024-07-01-225555

Steps to Convert Callbacks to Promises

To convert a callback-based function to a promise-based one, we typically use the Promise constructor. The basic idea is to wrap the callback inside a promise and resolve or reject the promise based on the outcome of the asynchronous operation.

Promises have four states:

  • Pending: The promise has not yet completed. It did not succeed and fail.
  • Fulfilled: The promise ended with success.
  • Rejected: The promise ended with an error.
  • Settled: The promise either gave an error or succeeded.

Wrap the Function in a Promise:

The first step is to create a new promise and call the original callback-based function inside the promise’s executor function.

const fs = require('fs');  function readFilePromise(filePath, encoding) {     return new Promise((resolve, reject) => {         fs.readFile(filePath, encoding, (err, data) => {             if (err) {                 reject(err); // Reject the promise if there's an error             } else {                 resolve(data); // Resolve the promise with the file content             }         });     }); }  // Usage readFilePromise('example.txt', 'utf8')     .then(data => console.log('File content:', data))     .catch(err => console.error('Error reading file:', err));

Error Handling:

Ensure that the reject function is called when there’s an error. This allows you to handle errors using .catch().

Chaining Promises:

You can chain multiple promises for sequential asynchronous operations. Each then block can return a value or another promise.

readFilePromise('example.txt', 'utf8')     .then(data => {         console.log('File content:', data);         return readFilePromise('anotherFile.txt', 'utf8');     })     .then(anotherData => {         console.log('Another file content:', anotherData);     })     .catch(err => console.error('Error:', err));

Example 1: This example Converts an existing callback to a Promise

Node
// app.js  // Existing Callback const callback = function (err, success) {     if (err) {         console.log("Geek is very sad!");     }     else {         console.log("Geek is optimistic, "             + "thus becomes successful");     } }  const caller = function (status, callback) {     if (status === 'Happy')         callback(null, true);     else {         callback(new Error(), false);     } }  // Calling the caller method  // Executes the success part caller('Happy', callback);  // Executes the error part caller('Sad', callback); 

Output:

Geek is optimistic, thus becomes successful Geek is very sad!

Approach:

  • First define a function named error and insert the error codeblock of callback function into it.
  • After that also define a function named success and insert the success codeblock into it.
  • Then modify the caller code by returning promise object.
  • Use the success and error methods in any of the following ways.
  • See the code snippet below for better understanding.

Example: Implementation to convert an existing callback to a promise in Node.js.

Node
// app.js  // This snippet briefly shows // the implementation const error = function () {      // The error codeblock from     // the existing callback.     console.log("Geek is very sad!"); }  const success = function () {      // The success codeblock from     // the existing callback     console.log("Geek is optimistic, "         + "thus becomes successful"); }  const caller = function (status) {     return new Promise(function (resolve, reject) {         if (status === 'Happy') {              // Calling the resolve function              // when function returns success             resolve();         }         else {              // Calling the reject function             // when function returns failure             reject();         }     }); };  // Throw success caller('Happy').then(success).catch(error);  // Throw error caller('Sad').then(success).catch(error); 

Output:

Geek is optimistic, thus becomes successful
Geek is very sad!

Let us change the following code snippet into a promise implementation. To make the implementation run, we need to set up a web app running on a node server. To understand using an example we need to set up a node server on the system. You can follow the following steps to set up a node server. Install node and set up a simple node application by following the steps as shown.

Example 2: Here, the scenario is that we have a student array having id and name as values. We need to get the name of the student having the given id. We are given an existing callback that needs to be converted to a promise.

Node
// app.js  /* Here we have a student array that stores JSON objects of student id and name. We are going to create a GET Request using expressjs in node first. Then we will write a route to get name of student based on id. */  const express = require('express'); const app = express();  // Students array let students = [     {         id: 101,         name: "Geek A"     },     {         id: 102,         name: "Geek B"     },     {         id: 103,         name: "Geek C"     },     {         id: 104,         name: "Geek D"     } ];  // Definition of the callback function const callback = (err, student) => {     if (err) {         return `Student with given id ${err} not found`;     }     else {         return "Here is the student: " + student.name;     } }  // Passing studentid and callback function as parameter const findName = (studentId, callbackFunction) => {     let student = students.find(function (studentValue) {         return studentValue.id == studentId;     });      // Student not found     if (typeof student === 'undefined') {         return callbackFunction(studentId, false);     }     else {  // Student found         return callbackFunction(null, student);     } }  const getName = (req, res) => {      // Sending back the response to the server     res.send(findName(req.params.studentId, callback)); }  app.get('/getName/:studentId', getName);  app.listen(8000, 'localhost', function () {     console.log('Server Listening'); }); 

Step to Run Application: Run the application using the following command from the root directory of the project

node app.js

Output:

Now, we can convert the callback function into promises. Here, we can follow the earlier steps again i.e. Error logic in the failure function and Success logic in the success function. Please see the below code for more clarity.

Node
// app.js  const express = require('express'); const app = express();  let students = [     {         id: 101,         name: "Geek A"     },     {         id: 102,         name: "Geek B"     },     {         id: 103,         name: "Geek C"     },     {         id: 104,         name: "Geek D"     } ];  // Writing the success logic here const success = (student) => {     return "Here is the student: " + student.name; }  // Writing the failure logic here. const failure = (fail) => {     return `Student with the given id ${fail} was not found`; }  const findName = (studentId) => {     return new Promise(function (resolve, reject) {         let student = students.find(function (studentValue) {             return studentValue.id == studentId;         });         if (student) {             resolve(student);         }         else {             reject(id);         }     }); }  const getName = async (req, res) => {     let answer = await findName(         req.params.studentId).then(success).catch(failure);      res.send(answer); }  app.get('/getName/:studentId', getName);  app.listen(8000, 'localhost', function () {     console.log('Server Listening'); }); 

Step to Run Application: Run the application using the following command from the root directory of the project

node app.js

Output:

Example: The example to demonstrate this is to use a setTimeout() function which accepts a callback and delays the execution of JavaScript code. As soon as the time set to function gets over, the callback function executes.

Node
// app.js  // Defining a callback function  const callback = () => {     console.log("Hello! GeeksforGeeks"); }  // Passing the callback function // as a parameter setTimeout(callback, 2000);  // The callback gets executed as // soon as 2 seconds are over. // This behavior shows the // execution of a callback. 

Output:

Hello! GeeksforGeeks


Next Article
How to convert an asynchronous function to return a promise in JavaScript ?

N

nvs87
Improve
Article Tags :
  • Node.js
  • Technical Scripter
  • Web Technologies
  • NodeJS-Questions
  • Technical Scripter 2019

Similar Reads

  • How to convert function call with two callbacks promise in Node.js ?
    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); })
    3 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.appendFile() method with promises in Node.js ?
    The fs.appendFile() 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 appendFile() method is used to append new data in the existing file or if the file does not exist then the file is created first
    4 min read
  • How to Create a Custom Callback in JavaScript?
    A callback is a function that executes after another function has been completed in JavaScript. As an event-driven language, JavaScript does not pause for a function to finish before moving on to the next task. Callbacks enable the execution of a function only after the completion of another, making
    3 min read
  • What is an error-first callback in Node.js ?
    In this article, we are going to explore the Error-first callback in Node.js and its uses. Error-first callback in Node.js is a function that returns an error object whenever any successful data is returned by the function. The first argument is reserved for the error object by the function. This er
    2 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 operate callback-based fs.mkdir() method with promises in Node.js ?
    The fs.mkdir() 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 mkdir() method is used to asynchronously create a directory. The fs.mkdir() method is based on callback. Using callback methods leads
    4 min read
  • How to Avoid Callback Hell in Node.js ?
    Callback hell, often referred to as "Pyramid of Doom," occurs in Node.js when multiple nested callbacks lead to code that is hard to read, maintain, and debug. This situation arises when each asynchronous operation depends on the completion of the previous one, resulting in deeply nested callback fu
    3 min read
  • How to Rewrite promise-based applications to Async/Await in Node.js ?
    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'read
    2 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