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
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Convert Callback to Promise in JavaScript ?
Next article icon

Promise vs Callback in JavaScript

Last Updated : 20 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, managing asynchronous operations is a key aspect of modern web development. Two popular approaches for handling these operations are Promises and Callbacks. While both techniques are designed to deal with tasks that take time to complete (like fetching data from a server), they work differently and have distinct advantages and drawbacks. This article explores Promises and Callbacks, their benefits, and the key differences between them.

What are Promises in JS?

To manage asynchronous actions in JavaScript, promises are used. It is an assurance that something will be done. The promise is used to keep track of whether the asynchronous event has been executed or not and determines what happens after the event has occurred.

A Promise has four states: 

  • fulfilled: Action related to the promise succeeded
  • rejected: Action related to the promise failed
  • pending: Promise is still pending i.e. not fulfilled or rejected yet
  • settled: Promise has fulfilled or rejected

Syntax:

Let promise = new Promise(function(resolve, reject){     // do something }); A promise can be created using Promise constructor.

Parameters:

  • Promise constructor takes only one argument which is a callback function (and that callback function is also referred as an anonymous function too).
  • Callback function takes two arguments, resolve and reject
  • Perform operations inside the callback function and if everything went well then call resolve.
  • If desired operations do not go well then call reject.

Example: In this example, a Promise is created to compare two strings, 'geeksforgeeks' and 'geeksforgeeks'. If the strings match, the promise resolves, logging a success message. Otherwise, it rejects, logging an error message. The then method handles success, and the catch method handles errors.

JavaScript
let promise = new Promise(function (resolve, reject) {     const x = "geeksforgeeks";     const y = "geeksforgeeks"     if (x === y) {         resolve();     } else {         reject();     } });  promise.     then(function () {         console.log('Success, You are a GEEK');     }).     catch(function () {         console.log('Some error has occurred');     }); 

Output
Success, You are a GEEK 

Benefits of Promises:

  • Improves Code Readability
  • Better handling of asynchronous operations
  • Better flow of control definition in asynchronous logic
  • Better Error Handling

What is Callback in JS ?

Callbacks are a great approach to dealing with something once another task has been finished. Here, "something" refers to the execution of a function. Callbacks can be utilized if we wish to run a function immediately following the return of another function.

The type of JavaScript function is objects. They may therefore be supplied as an argument to any other function when calling them, just like any other objects (Strings, Arrays, etc.).

Example : In this example, the add function takes two numbers, adds them, logs the result, and executes a callback function (disp). When calling add(5, 6, disp), it outputs the sum and a message from the callback.

JavaScript
// The add() function is  // called with arguments a, b // and callback, callback  // will be executed just // after ending of add() function function add(a, b, callback) {     console.log(`The sum of ${a}      and ${b} is ${a + b}`);     callback(); }  // The disp() function is called just // after the ending of add() function function disp() {     console.log(`This must be printed      after addition`); }  // Calling add() function add(5, 6, disp) 

Output
The sum of 5      and 6 is 11 This must be printed      after addition 

Explanation:

Here are the two functions – add(a, b, callback) and disp(). Here add() is called with the disp() function i.e. passed in as the third argument to the add function along with two numbers.

As a result, the add() is invoked with 1, 2, and the disp() which is the callback. The add() prints the addition of the two numbers and as soon as that is done, the callback function is fired! Consequently, we see whatever is inside the disp() as the output below the additional output.

The benefit of Callback:

  • You can run another function call after waiting for the outcome of a prior function call.
  • You can call the parent function from the child function and can also pass data from child to parent.

Difference:

 PropertiesJavaScript CallbackJavaScript Promise
SyntaxThe syntax is difficult to understand.The syntax is user-friendly and easy to read because of then and catch.
Error handlingError handling may be hard to manage.Error handling is easier to manage using catch block.
Callback hellIt may create callback hell.It resolves callback hell.

Conclusion

While both Promises and Callbacks serve the same purpose of handling asynchronous operations, Promises offer a more organized, readable, and manageable way to write code. Promises resolve the issues associated with nested callbacks and provide better error handling. As JavaScript has evolved, Promises (along with async/await) have become the preferred method for managing asynchronous logic in modern development.

How do Promises help avoid callback hell?

Promises flatten nested callback structures, making the code easier to read and manage by chaining .then() and .catch() methods instead of deeply nested functions.

What is callback hell and how do Promises resolve it?

Callback hell occurs when multiple asynchronous operations are nested within each other, leading to unreadable code. Promises resolve this by allowing flat, sequential chaining of asynchronous operations.

Can Promises be used alongside callbacks?

Yes, Promises and callbacks can be used together. For example, you can wrap a callback-based function in a Promise to take advantage of the benefits of both approaches.

How is error handling different between Promises and Callbacks?

In callbacks, error handling can be tricky, requiring manual checks. In Promises, errors are automatically caught and handled in the .catch() block, making error management easier and more reliable.


Next Article
How to Convert Callback to Promise in JavaScript ?
author
akashjha2671
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • Technical Scripter 2022
  • JavaScript-Questions

Similar Reads

  • 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
  • JavaScript Promise Chaining
    Promise chaining allows you to execute a series of asynchronous operations in sequence. It is a powerful feature of JavaScript promises that helps you manage multiple operations, making your code more readable and easier to maintain. Allows multiple asynchronous operations to run in sequence.Reduces
    3 min read
  • JavaScript Callbacks
    In JavaScript, callbacks play an essential role in handling asynchronous tasks like reading files, making API requests, and executing code after certain events. If you’ve ever heard the phrase "I will call back later!", that’s exactly how callbacks work. What is a Callback Function?A callback functi
    5 min read
  • JavaScript Promise
    JavaScript Promises make handling asynchronous operations like API calls, file loading, or time delays easier. Think of a Promise as a placeholder for a value that will be available in the future. It can be in one of three states Pending: The task is in the initial state.Fulfilled: The task was comp
    5 min read
  • JavaScript Promise all() Method
    The Promise.all() method in JavaScript is used for handling multiple asynchronous operations simultaneously. It takes an array (or any iterable) of promises and returns a single promise that resolves when all the input promises resolve or reject if any one of the promises fails. This makes it ideal
    6 min read
  • JavaScript Promise catch() Method
    JavaScript Promise catch() method is called whenever a promise is rejected. This method itself returns a promise so it can also be used to chain promises. This method is used for error handling. This method is mainly used after .then to chain a promise and handle reject condition. This method intern
    2 min read
  • What is Callback Hell in JavaScript ?
    One of the primary ways to manage asynchronous operations in JavaScript is through callback functions that execute after a certain operation completes. However, excessive use of callbacks can lead to an issue known as Callback Hell, making code difficult to read, maintain, and debug. What is Callbac
    4 min read
  • JavaScript - How to Handle Errors in Promise.all?
    To handle errors in Promise.all(), you need to understand that it fails immediately if any of the promises reject, discarding all resolved values. This behavior can lead to incomplete operations and potential application crashes. The best way to manage errors in Promise.all() is by using .catch() in
    3 min read
  • JavaScript Promise any() Method
    JavaScript Promise any() method is a static method that takes an array of promises as a parameter and returns the first fulfilled promise. It returns a rejected value when all of the promises in the array return rejects or if the array is empty. When all the promises are rejected an AggregateError i
    2 min read
  • JavaScript Passing parameters to a callback function
    Callback FunctionPassing a function to another function or passing a function inside another function is known as a Callback Function. In other words, a callback is an already-defined function that is passed as an argument to the other code Syntax:function geekOne(z) { alert(z); }function geekTwo(a,
    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