Callback & Promise in JavaScript

A Promise is a new feature in ES6 JavaScript.

A promise is an object that may produce a single value some time in the future. It will be resolved a value or it will not be resolved (rejected).

A promise in one of three possible state Rejected

  1. Fullfilled
  2. Rejected
  3. Pending

Before promise, JavaScript only have callbacks.

Callbacks are the cornerstone of asynchronous JavaScript programming, and callback is a function passed into another function as an argument to be executed later.

Example of Callback

let foods = ["apple", "blueberry", "Mango"];
foods.forEach(function callback(food){
    console.log(food);
});
apple
blueberry
Mango

Also, Passing a callback as a predefined function

let foods = ["apple", "blueberry", "Mango"];

function a(food){
    console.log(food)
}
foods.forEach(a);
apple
blueberry
Mango
  • function a is used as callback function.

Create our own callback function

function a(callback) {
    callback("callback is working")
}

a(function (data) {
    console.log(data)
});
callback is working

However, callback you can get the nested function which called as “Callback Hell“. So, sometimes you need promise for code readability.

Promise with multiple callback.

let promise = new Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve('Hello World');
    }, 1000);
});

promise.then(function (data) {
    console.log(data)
    return data + " I like you"
}).then(function (data) {
    console.log(data)
}).then(function (data) {
    console.log(data)
}).catch(() => console.log("error!"))
first layer: Hello World
second layer: Hello World I like you
third layer: undefined

After one second “Hello world” is resolved which is used in first layer and first layer return another value which is used second layer with no return, so third layer data is undefined.

You can use a promise with the task happens such as APIs Call. When the promise gets resolved or rejected then you will get the response.

More Promise Example

let promise1 = new Promise((resolve, reject) => {
    setTimeout(function () {
        resolve('Hello');
    }, 50);
})

let promise2 = new Promise((resolve, reject) => {
    setTimeout(function () {
        resolve('World');
    }, 500);
})

let promise3 = new Promise((resolve, reject) => {
    setTimeout(function () {
        resolve('With Promise');
    }, 5000);
})

Promise.all([promise1, promise2, promise3]).then(x => {
    console.log(x)
})
[ 'Hello', 'World', 'With Promise' ]
  • After 5 Second Promise.all resolved.

A Promise can only succeed or fail only once. It can not succeed or fail twice, and this is extremely useful for things that are asynchronous success and failure such as APIs calls. Fetch Simple returns a promise.

Leave a Reply

Your email address will not be published.

ANOTE.DEV