# 如果每隔 1s 输出应该如何改造?

const list = [1, 2, 3]
const square = num => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(num * num)
    }, 1000)
  })
}

function test() {
  list.forEach(async x=> {
    const res = await square(x)
    console.log(res) 
  })
}
test()

// 1
// 4
// 9

分析原因:forEach是不能阻塞的,默认是请求并行发起,所以是同时输出1、4、9。

开始改造:串行解决方案。

(1)使用for循环

async function test() {
  for (let i = 0; i < list.length; i++) {
    let x = list[i]
    const res = await square(x)
    console.log(res)
  }
}

(2)使用for of

async function test() {
  for (let x of list) {
    const res = await square(x)
    console.log(res)
  }
}

(3)使用Promise链式调用

let promise = Promise.resolve()
function test(i = 0) {
  if (i === list.length) return
  promise = promise.then(async () => {
    const res = await square(i + 1)
    console.log(res)
  })
  test(i + 1)
}
test()