What are the features of native promise. all?

  1. Attribute 1: Receives an iterable
  2. Feature 2: The incoming data can be normal data or a Promise object
  3. Feature 3: Iterable promises are executed in parallel
  4. Feature 4: Keep the order of the input array the same as the order of the output array
  5. Attribute 5: Reject is returned immediately whenever there is a Reject in the passed array
  6. Feature 6: All data returns after resolve

Realize the Promise. All

1: The function returns a Promise object

function myPromiseAll(可迭代) {
    return new Promise((resolve,reject) = >{})}Copy the code

2: Converts an iterable to an array

const promises = Array.from(iterable);
Copy the code

3: Execute each Promise concurrently

// Define a counter to determine if all promises have been fulfilled
let count = 0;
// Execute each promise concurrently
for (let i = 0; i < promises.length; i++) {
    Promise.resolve(promises[i]).then(res= > {
        result[i] = res;
        count++;
        if (count === promises.length) {
            resolve(result);
        }
    }).catch(err= > reject(err))
}
Copy the code

The third step is to realize the Promise. All core, we need to pay attention to the following points:

  1. We don’t push it into the result array, we store it by subscript, because we want to keep the order of the output, because Promise objects might execute at different times, and push would break the order.
  2. Count flags to determine if all promise objects have been executed, because then indicates that the promise object has been executed.

Complete implementation

function myPromiseAll(可迭代) {
    return new Promise((resolve,reject) = > {
        const promises = Array.from(iterable);
        // Define an array of the Promise object resolve
        const result = [];
        // Define a counter to determine if all promises have been fulfilled
        let count = 0;
        // Execute each promise concurrently
        for (let i = 0; i < promises.length; i++) {
            Promise.resolve(promises[i]).then(res= > {
                result[i] = res;
                count++;
                if (count === promises.length) {
                    resolve(result);
                }
            }).catch(err= > reject(err))
        }
    })
}
Copy the code

What does the realization of promise.all give us

  • Promise.all returns a Promise object
  • Promise.all receives an Array of iterables that needs to be converted to an Array by array. from
  • Promise.all is executed concurrently.
  • A reject in promise. all returns a reject.