1. What are the methods on promises

Before we start writing the code, we need to make a classification of the methods that promises can use: methods on promise objects and methods on promises.

As you can see from the figure above, the methods defined on the prototype object are:

  • catch
  • then
  • finally

The method defined in the constructor is:

  • all
  • race
  • reject
  • resolve

Methods on constructors can be called directly through promise.all (), but objects defined on prototypes need to be called through (new Promise(()=>{})).then().

2. Promise. The role of all

For promise.all () is mainly used for parallel processing. When there are multiple Promise objects, we can put them into ALL for processing. All will return results only when all the Promise objects passed in are in resolved state. Otherwise, the error result is processed.

parameter

Because you need to process multiple Promises, the argument is an array of Promises

The return value

After the promise.all () call, the result is returned in the order of the sequential array arguments, and the return value is a Promise object.

3. Promise. All () implementation

  1. First, this method is defined directly on the Promise
  2. The parameter must be array. If the parameter is not array, an error message is displayed
  3. The return value is a Promise object
  4. This must be controlled so that only all promises in the array are in the Resolved state will return a value
  5. When one of the Promise objects has a state of Rejected, it returns immediately and is not executed again
    Promise.myAll=function(promises){
        return new Promise((resolve,reject) = >{
            if(!Array.isArray(promises)){
                    throw new Error("Parameter must be an array");
            }
            let resolvedCount=0;
            let promiseLength=promises.length;
            let resolvedResult=[];
            for(let i=0; i<promises.length; i++){Promise.resolve(promises[i]).then((value) = >{
                            resolvedCount++;
                            resolvedResult[i]=value;
                            if(resolvedCount===promiseLength){
                                    returnresolve(resolvedResult); }},error= >{ reject(error); })}})}Copy the code

ResolvedResult [I]=value; resolvedResult[I]=value; Index is used to add array data. Since it is an asynchronous task, there is no guarantee of the order returned by the asynchronous execution. So we need an index to ensure that the final result is returned in exactly the same order as the arguments in promise.all ().

If there is any problem with the above content, please point out oh ~