order promise.all with arr.reduce code example

Example 1: javascript reduce promises

const sum = await [
  Promise.resolve(1),
  Promise.resolve(1),
  Promise.resolve(1)
].reduce(async (previousPromise, itemPromise) => {
  const sum = await previousPromise;
  const item = await itemPromise;
  return sum + item;
}, Promise.resolve(0))

// sum === 3

Example 2: es6 reduce return promise

async function slowCounter () {
    const ret = await ([100, 200, 300, 400, 500]).reduce(
        async (promise, wait, idx) => {
            return promise.then(async last => {
                const ret = last + wait
                console.log(`${idx}: waiting ${wait}ms to return ${ret}`)
                await new Promise((res, rej) => setTimeout(res, wait))
                return ret
            })
        }, Promise.resolve(0))
    console.log(ret)
}

slowCounter ()