Promise.all 的原理


// all的原理
Promise.all = function(values){
    return new Promise((resolve,reject)=>{
        let results = []; // 結果數組
        let i = 0;
        let processData = (value,index)=>{
            results[index] = value;
            // 當成功的個數 和 當前的參數個數相等就把結果拋出去
            if(++i === values.length){
                resolve(results);
            }
        }
        for(let i = 0 ; i< values.length;i++){
            let current = values[i]; // 拿到數組中每一項
            // 判斷是不是一個promise
            if((typeof current === 'object' &&  current !==null)|| typeof current == 'function'){
                // 如果是promise
                if(typeof current.then == 'function'){
                    // 就調用這個promise的then方法,把結果和索引對應上,如果任何一個失敗了返回的proimise就是一個失敗的promise
                    current.then(y=>{
                        processData(y,i);
                    },reject)
                }else{
                    processData(current,i);
                }
            }else{
                processData(current,i);
            }
        }
    });
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM