for await..of 有什么作用?

  • for await..of 用于遍历多个 Promise
  function createPromise(val) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve(val)
          }, 1000)
        })
      }
      ;(async function () {
        const p1 = createPromise(100)
        const p2 = createPromise(200)
        const p3 = createPromise(300)

        //方法一
        // const res1 = await p1
        // console.log(res1)
        // const res2 = await p2
        // console.log(res2)
        // const res3 = await p3
        // console.log(res3)

        const list = [p1, p2, p3]
        //方法二
        Promise.all(list).then(res => console.log(res))
        //方法三
        for await (let v of list) {
          console.log(v)
        }
        //方法四
        const res1 = await createPromise(100)
        console.log(res1)
        const res2 = await createPromise(200)
        console.log(res2)
        const res3 = await createPromise(300)
        console.log(res3)
      })()
posted @ 2022-04-15 23:03  awsoyou  阅读(206)  评论(0)    收藏  举报