使用 Promise 实现定时输出

用 Promise 和 reduce 实现每隔 1 秒依次输出数组元素

问题

使用 Promise 实现每隔 1 秒输出 1, 2, 3。

解答

基础实现

使用 reduce 配合 Promise 链式调用,不断在后面叠加 .then()

const arr = [1, 2, 3]
arr.reduce((p, x) => {
  return p.then(() => {
    return new Promise(r => {
      setTimeout(() => r(console.log(x)), 1000)
    })
  })
}, Promise.resolve())

简化写法

const arr = [1, 2, 3]
arr.reduce(
  (p, x) => p.then(() => new Promise(r => setTimeout(() => r(console.log(x)), 1000))), 
  Promise.resolve()
)

关键点

  • 使用 reduce 将数组转换为 Promise 链
  • 初始值为 Promise.resolve() 确保第一次调用有 Promise 对象
  • 每次 then 返回新的 Promise,形成串行执行
  • setTimeout 控制每次输出的时间间隔