JS嵌套ajax+setInterval,怎样改成同步请求?

作者站长头像
站长
· 阅读数 9

怎样让下面这段代码变成同步,顺序的打印出1 0 0 0 2 0 0 0 3 0 0 0 4 5

func() {
  console.log(1)
  const arr = [2, 3, 4]
  arr.forEach((num, idx) => {
    this.$http.get('a-url').then(() => {
      const interval = setInterval(() => {
        let i = 0
        this.$http.get('b-url').then(() => {
          i = i + 1
          console.log(0)
          if(i === 3) {
            clearInterval(interval)
          }
        })
      }, 1000)
    })
    console.log(num)
  })
  console.log(5)
}
回复
1个回答
avatar
test
2024-07-11
async func() {
    console.log(1)
    const arr = [5, 6, 7]

    for (const num of arr) {
      await this.$http.get("a-url");
      let i = 1;
     await new Promise((resolve, reject)=>{
       const interval = setInterval(async () => {
         i = i + 1
         await this.$http.get("b-url")
         num<6&&console.log(i)
         if(i === 4) {
           clearInterval(interval)
           resolve()
         }
       }, 1000)
      })
      console.log(num)
    }
    console.log(8)
  }
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容