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:
Implement polyfill for Array.prototype.map() method in JavaScript
Next article icon

Implement polyfill for Promise.all() method in JavaScript

Last Updated : 14 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Implement polyfill for Array.prototype.map() method in JavaScript
author
sakshi_srivastava
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • Implement polyfill for Array.prototype.map() method in JavaScript
    In this article, we will learn how to implement a polyfill for an Array.prototype.map() method 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 of the older version of the browser y
    3 min read
  • Implement polyfill for Array.prototype.reduce() method in JavaScript
    In this article, we will learn how to implement a polyfill for an Array.prototype.reduce() method in JavaScript. 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 of the older version of the browser you are using, or
    2 min read
  • Polyfill for Array.prototype.filter Method in JavaScript
    In JavaScript, the Array.prototype.filter method is the powerful tool for creating a new array containing the elements that meet specific criteria by the callback function. However, in the order environments or browsers, this method might not be available. In such cases, we can create the polyfill t
    3 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
  • How to Implement a Custom Promise in JavaScript ?
    A custom Promise in JavaScript encapsulates asynchronous operations. It takes two parameters, resolves and rejects functions, and executes an async task. Resolve is called on success with the result, while reject is called on failure with an error. Table of Content Using Class SyntaxUsing Factory Fu
    3 min read
  • JavaScript Promise allSettled() Method
    Promise.allSettled() method in JavaScript is used to handle multiple promises concurrently and return a single promise. This promise is fulfilled with an array of promise state descriptors, each describing the outcome of the corresponding promise in the input array. Unlike Promise.all(), Promise.all
    2 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 Promise finally() Method
    The finally() method of the Promise object is used to return a callback when a Promise is settled (either fulfilled or rejected). Syntax:task.finally(onFinally() { });Parameters: This method has a single parameter as mentioned above and described below: onFinally: It is the function that will be cal
    1 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
  • How to use Polyfill in JavaScript ?
    A polyfill in JavaScript is a script that adds modern features to older browsers that do not natively support them. To use it, include the polyfill script in your HTML or install it via a package manager, ensuring compatibility with older environments. Polyfill and its featuresBroad Compatibility: P
    3 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