js中如何遍历异步数组

969 阅读1分钟

通常数组的遍历是按照顺序依次进行的,如果数据中涉及异步,此时数据在数组中的位置就不那么重要,通常可以使用redcue结合promise解决异步数组的遍历问题

有如下的数组:

const make = (n, duration) => new Promise(() => setTimeout(() => console.log(n), duration))

let arr = [make(5, 1000), make(7, 500), make(2, 100), make(1, 600), make(8, 800)]

定时器的时间长度输出

arr.forEach(v => v.then(console.log.bind))
=>  2 -> 7 -> 1 -> 8 -> 5

顺序输出

arr.reduce((p, v) => p.then(() => v.then(console.log)), Promise.resolve())
5 -> 7 -> 2 -> 1 -> 8