在循环里使用async await

186 阅读1分钟
// 模拟异步操作
const delay = (val) => {
    return new Promise((resolve, reject) => {
        setTimeout(resolve(val), 800 * val)
    }
}

在for...of中使用

const test = async () => {
    const arr = [1, 2, 3]
    for (let i of arr) {
        const res = await delay(i)
        conosole.info(res)
    }
    console.info('game over!')
}

在for循环中使用

const test = async () => {
    const arr = [1, 2, 3]
    for (let i=0; i < arr.length; i++) {
        const res = await delay(i)
        console.info(res)
    }
    console.info('game over!')
}

在while循环内使用

const test = async () => {
    const arr = [1, 2, 3]
    let i = 0
    while(i !== arr.length) {
        const res = await delay(arr[i]
        console.info(res)
    }
    console.info('game over!')
}

在forEach中不能使用async await, 因为forEach的内部机制是直接调用函数,而for...of等是通过迭代器去执行的。

通过迭代器执行

const test = async () => {
  const arr = [1, 2, 3]
  const iterator = arr[Symbol.iterator]()
  const res = iterator.next()
  while (!res.done) {
    const value = res.value
    const res1 = await delay(value)
    console.info(res1)
    res = iterator.next()
  }
  console.info('game over!')
}