DAY 23
0

## 利用30分鐘～想一個前端問題 Day23-runPromisesInSeries

runPromisesInSeries

Runs an array of promises in series.

Use Array.prototype.reduce() to create a promise chain, where each promise returns the next promise when resolved.

``````const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
//EXAMPLES
const delay = d => new Promise(r => setTimeout(r, d));
runPromisesInSeries([() => delay(1000), () => delay(2000)]); // Executes each promise sequentially, taking a total of 3 seconds to complete
``````

### 分析點

1.reduce()

``````arr.reduce(callback[accumulator, currentValue, currentIndex, array], initialValue)
``````

reduce()方法接收一個函數作為累加器，陣列的每個數（從左到右）開始縮減

reduce 為陣列的每一個元素依次執行回調函數，不包括陣列中被刪除或從未被賦值的元素，接受四個參數：

• accumulator - 上一輪累計加總
• currentValue -陣列中正在處理的元素
• currentIndex - 陣列中正在處理的當前元素的索引(可省略)
• array - 陣列內容(可省略)
• initialValue - 累計處理的結果
``````const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
``````

``````
let result = [1,2,5].reduce((accumulator,item)=>{
return accumulator + item
},0) // initial value

console.log(result);

``````

``````function myPromiseQuene(myPromise){
myPromise.reduce(prePromise,nextPromise)=>prePromise.then(()=>nextPromise()),Promise.resoleve()
}
``````

``````new Promise((resolve,reject)=>{
resolve()
}).then(result=>{
return  result //#promise1
}).then(result=>{
return  result //#promise2
}).then(result=>{
return  result //#promise3
})
``````

reduce 的作用就是在內存中生成這個陣列，而不需要把這個冗餘的陣列寫在代碼裡！

``````[1, 2, 3, 4].reduce(
(p, current) => p.then(() => delayPromise(current)),
Promise.resolve()
)
/* 等效於
Promise.resolve()
.then(()=>delayPromise(1))
.then(()=>delayPromise(2))
.then(()=>delayPromise(3))
.then(()=>delayPromise(4))
*/
``````

reduce 陣列用法