Logo

dev-resources.site

for different kinds of informations.

Understanding JavaScript Promises and Callbacks

Published at
3/19/2024
Categories
javascript
promises
callback
asynchronous
Author
jenishdabhi
Author
11 person written this
jenishdabhi
open
Understanding JavaScript Promises and Callbacks

As JavaScript programmers, we frequently deal with asynchronous tasks in our applications. Managing these tasks can be challenging, but JavaScript Promises provides a neat and effective approach to handling them.

What are JavaScript Promises?
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.

Promises are similar to real-life commitments we make in our daily lives. For example, consider a scenario where you make a promise to your friends that you will take them to a party next weekend. However, in reality, you’re uncertain whether you’ll have time on the weekend or not. This means that you might not be able to fulfill that promise.

So there may be three chances:

  • Pending: You don't know whether you will have time or not.
  • Fulfilled: You gave them a party.
  • Rejected: You didn't give a party to them.

A Promise starts with the pending state, then moves to either the fulfilled or rejected state after the asynchronous operation is completed.

See below example :

function makePromise(partyPromise) {
 return new Promise(function (resolve, reject) {
    setTimeout(() => {
        if (partyPromise) {
            resolve("I given party to friends");
        } else {
            reject("I am not given party to friends");
        }
    }, 5 * 1000);
});
}
let partyPromise = makePromise(true);
partyPromise
    .then(success => console.log(success))
    .catch(reason => console.log(reason))
    .finally(() => console.log("Friends are ready for party !"))
Enter fullscreen mode Exit fullscreen mode

The Benefits of Promises:

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

What are Callback Functions?

A callback function in JavaScript is a function that is passed as an argument to another function and is executed inside the outer function to complete some kind of routine or action. Callback functions help us manage asynchronous operations, making our code more organized and easier to understand.

Basic Syntax of a JavaScript Callback Function

function greet(name, callback) {
  console.log(`Hello, ${name}!`);
  callback();
}

greet('Jenish', function () {
  console.log('This is a callback function');
});
Enter fullscreen mode Exit fullscreen mode

In the example above, we define a greet function that accepts two arguments: a name and a callback function. After logging a greeting message, the greet function executes the callback function.

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

Callback vs Promises

  • A callback function is passed as an argument to another function, whereas a promise is an object that you interact with using its methods, such as then and catch.
  • Promises are chainable, meaning that multiple operations can be queued up and executed in order, unlike callbacks which would require callback hell.

Thank you for reading.
Happy coding!

asynchronous Article's
30 articles in total
Favicon
Why is My Multi-Threaded API Still Slow?
Favicon
Building Async APIs in ASP.NET Core - The Right Way
Favicon
Understanding Synchronous and Asynchronous Bus Timing
Favicon
Async Vs Sync, which is most preferrable?
Favicon
Mastering Asynchronous Programming in JavaScript
Favicon
Why Modern Programming Isn't Always Asynchronous (And That's Okay, Mostly)
Favicon
Zero-Cost Abstractions in Rust: Asynchronous Programming Without Breaking a Sweat
Favicon
Why Wait? Exploring Asynchronous and Non-Blocking Programming 🚦
Favicon
The Tale of Async, Multithread, and Parallel: Heroes of the .NET Realm
Favicon
Getting Started with Asynchronous Programming in Dart
Favicon
JavaScript Event Loop
Favicon
Asynchronous programming in Javascript
Favicon
This Week I Learnt: Java's CompletableFuture
Favicon
How to Run a Method Asynchronously in a Reactive Chain in Spring WebFlux?
Favicon
Programación asincrónica en Javascript
Favicon
Understanding the Event Loop, Callback Queue, and Call Stack & Micro Task Queue in JavaScript
Favicon
Mastering Callbacks in JavaScript 💻🔥
Favicon
Mastering Concurrency in C with Pthreads: A Comprehensive Guide
Favicon
Async/Await keeps order in JavaScript;
Favicon
Rate my python async snippet
Favicon
Returning a Promise — How an async function operates
Favicon
A Project of async springboot and react js from where i can learn please help...
Favicon
GPT teaches me how to make my logic sync and async at the same time with trampolines
Favicon
Understanding JavaScript Promises and Callbacks
Favicon
Pros and Cons of Event-Driven Architecture
Favicon
Asynchronous Communication with Apache Kafka
Favicon
Dig deeper into JavaScript.
Favicon
Is async/await a good idea? 🤔 async/await vs promises
Favicon
What is RabbitMQ and why do you need a Message Broker?
Favicon
🍳 Asynchronous Programming in C# Made Easy: Breakfast Included! ☕️

Featured ones: