JavaScript 循环数组的时候调用方法中包含Promise的时候如何做到串行

forEach是不能阻塞的, 默认【并行】方式

const list = [1, 2, 3]
const square = num => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (isNaN(num)) {
        reject(new TypeError(`${num} is not a number`))
      } else {
        resolve(num * num)
      }
    }, 1000)
  })
}

// 并行
function parallelTest() {
  // 🚀 forEach是不能阻塞的,默认是请求【并行】发起,所以是同时输出1、4、9
  list.forEach(async x => {
    const res = await square(x)
    console.log(res)
  })

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

const res = square(7)
res.then(x => console.info(x)) // 49

parallelTest()

seriesTest()
posted @ 2020-08-05 15:28  荣光无限  阅读(674)  评论(0编辑  收藏  举报