在setInterval中使用await没有效果

新手上路,请多包涵
    p() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("settimeout")
        }, 2000);
      });
    },
    async f() {
      const that = this
      const t = setInterval(async function() {
        console.log('setInterval')
        const x =await that.p();
        console.log(x)
      }, 2000);
    },

1586311926(1).jpg


setInterval没有等待setTimeout就直接进入下一轮

阅读 4.6k
4 个回答

setInterval 只是调用函数而已,函数是否执行完它不关心,所以到时候就继续调用了。

~function p() {
  console.log(1)
  new Promise(() => {
    setTimeout(() => {
      p()
    }, 2000);
  })
}()

这样试试

    p() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("settimeout")
        }, 2000);
      });
    },
    async f() {
      const that = this
      console.log('setInterval')
      const x =await that.p();
      console.log(x)
      setTimeout(that.f, 2000)      
    },

你没有搞懂even loop 建议搞懂这个 这个基本操作

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题