Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptImplement polyfill for Promise.all() method in JavaScript

Implement polyfill for Promise.all() method in JavaScript

The task is to write a polyfill for Promise.all methods in javascript.

What is a Polyfill?

A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because the older version of the browser you are using, or the new version of the browser does not have that feature.

 

What is Promise.all()?

The Promise.all() method is actually a method of the Promise object (which is also an object under JavaScript used to handle all the asynchronous operations), that takes an array of promises(an iterable) as input. It returns a single Promise that resolves when all of the promises passed as an iterable, which have resolved, or when the iterable contains no promises. In a simple way, if any of the passed-in promises reject, the Promise.all() method asynchronously rejects the value of the promise that has already been rejected, whether or not the other promises have been resolved. 

Syntax:

Promise.all( iterable )

Parameters: This method accepts a single parameter iterable which takes an array of promises or a normal array that contains some objects.

Return values: It follows some rules to return a single promise: 

  • If the passed argument is empty, it returns a Promise that is already resolved.
  • If the passed iterable contains no promises, it returns a Promise that is resolved asynchronously.
  • For all other cases, it returns a pending Promise.

Fulfillment and Rejection of Promise.all() Method: 

Fulfillment: The returned promise is fulfilled, 

  • If the passed iterable is empty, then this method returns a promise synchronously which is already resolved.
  • If all of the passed promises are fulfilled, the returned Promises are fulfilled asynchronously.
  • Here the successful execution of this particular method totally depends on all promises to get successfully executed.

Rejection: If any of the passed promises are rejected, then this method rejects the value of that promise, whether or not the other promises have been resolved. 

Let’s see some JavaScript Promise.all() method examples:

Example 1:

Javascript




const p1 = Promise.resolve(3);
const p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("foo");
    }, 100);
});
  
Promise.all([p1, p2]).then((values) => {
    console.log(values);
});


Output:

[3, "foo"]

Example 2:

Javascript




const prom1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Resolved First after 1 second");
    }, 1000);
});
  
const prom2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Resolved First after 2 seconds");
    }, 2000);
});
  
const prom3 = 20;
  
try {
    let result = Promise.all([prom1, prom2, prom3]);
    result.then((data) => console.log(data));
} catch (error) {
    console.log(error);
}


Output:

[
    'Resolved First after 1 second',
    'Resolved First after 2 seconds',
    20
]

Let’s implement polyfill for Promise.all

Approach:

  1. We will create a myall function which will take an array of promises as input
  2. In the myall function we will do below:
    1. We will declare a const variable named a promise, a result that will store the result of all the promises, and a total that will keep count of how many promises have resolved with values.
    2. we will create a new promise, inside the promise we will iterate over all the promises received as input, and whenever an input promise resolves we will increment the total and we will store the resolved value in the result array at the same index where the promise was present. If the total is equal to the input array’s length then we will resolve with the result array. If the promise rejects with an error then straight away we will reject it with the same error.

Javascript




const prom1 = new Promise(function (resolve, reject) {
    setTimeout(() => {
        resolve("gfg1")
    }, 1000)
})
  
const prom2 = new Promise(function (resolve, reject) {
    setTimeout(() => {
        reject("error")
    }, 2000)
})
  
const prom3 = new Promise(function (resolve, reject) {
    setTimeout(() => {
        resolve("gfg2")
    }, 3000)
})
  
const prom4 = new Promise(function (resolve, reject) {
    setTimeout(() => {
        resolve("gfg3")
    }, 3000)
})
  
Promise.myall = function (values) {
    const promise = new Promise(function (resolve, reject) {
        let result = [];
        let total = 0;
        values.forEach((item, index) => {
            Promise.resolve(item).then((res) => {
                result[index] = res;
                total++;
                if (total === values.length)
                    resolve(result);
            }).
                catch((err) => {
                    reject(err);
                })
        })
    })
    return promise
}
  
Promise.myall([
    prom1,
    prom2,
    prom3
])
    .then((res) => {
        console.log(res);
    })
    .catch((er) => {
        console.log(er)
    })
  
Promise.myall([
    prom1,
    prom3,
    prom4
])
    .then((res) => {
        console.log(res);
    })
    .catch((er) => {
        console.log(er)
    })


Output:

"error"
["gfg1", "gfg2", "gfg3"]

Explanation: In the first case since prom3 throws an error so the Promise.all rejects with the error message.
In the second case since all the promises resolve with some value hence Promise.all resolves with an array of the resolved values of the three promises.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments