Tag Archives: JS Promise.all

JS native implementation Promise.all

I met an interesting interview question today, which asked me to implement promise.all
with js native. Since I was not familiar with this API, I only realized the function of “resolve” and “callback”
Promise. All description

    promise.all (iterable) method returns a Promise instance in which all promises in the iterable parameter are “resolved” or arguments containing no Promise. If the Promise has a rejected in the parameter, the instance will call back reject because of the result of the first failed Promise

JS implements the all method

function all(iterableArr) {
    //Returns a PROMISE instance (satisfying the first rule)
    return new Promise((resolve,reject)=>{
        //resArr is used to store all the resolve promises of the resolve
        let resArr = [];
        // iterate through all elements of the array.
        for(let i in iterableArr){  
            let cur = iterableArr[i];
            // If the current object is of type promises
            if(typeof cur === 'object' && typeof cur.then ==='function'){ 
                cur.then((res)=>{
                    resArr[i] = res;
                    //If all resolve, the length of the stored resArr is the same as the length of the incoming iterableArr, and the entire promise is then resolve (in accordance with the second rule).
                    if(resArr.length === iterableArr.length){
                        resolve(resArr);
                    }
                // If the state of the current instance of promise is reject, then the entire promise will be reject. (The third rule is met.)
                },reject) 
            }else{
                resArr[i] = cur
            }
        }
    })
}

//Test
all([
    Promise.reject(100),//Promise.resolve(100)
    123,
    new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve("DD")
        },5000)
    })
]).then((res)=>{
    console.log(res)
}).catch((err)=>{
    console.log(err)
})

The above