// 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); } } }); }