javascript - setTimeout 与 Promise 一起使用时的不明确行为

标签 javascript node.js promise settimeout

我想每 x 秒在 Promise 中运行一个异步方法,直到满足特定条件,然后调用 resolve() 来解析 Promise。我尝试使用两种方法(如下所示)。第二种方法是使用 IIFE 设计的,并给出了正确的结果,但在第一种方法中,setTimeout 方法仅运行一次,但根据 def. setTimeout 应该在指定的时间后无限期地执行回调,直到调用 clearTimeout() 为止。谁能向我解释为什么我在第一种方法中没有得到所需的输出?

方法 1

function func2() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {

            client.get('statuses/user_timeline', params1).then((response) => {
                //    some code
                //    some code

                if (condition is met) {
                    return resolve()
                } else {
                    //    some code
                }
            })
        }, 1000)
    })
}

方法 2

function func2 () {
    return new Promise((resolve, reject) => {
        (function func1() {
            client.get('statuses/user_timeline', params1).then((response) => {
                //    some code
                if (condition is met) {
                    return resolve()
                } else {
                    //    some code
                    setTimeout(func1, 1000)
                }
            })
        })()
    }
}

最佳答案

setTimeout() 仅执行该函数一次,我认为您正在寻找 setInterval()。它的工作方式相同,但在无限期执行该函数时,会调用它的 clearInterval() 单元。

这将是你的功能:

function func2() {
return new Promise((resolve, reject) => {
  let interval = setInterval(() => {

  client.get('statuses/user_timeline', params1).then((response) => {
    //    some code
    //    some code

    if (condition is met) {
      clearInterval(interval)
      return resolve()
  } else {
    //    some code
  }
})
}, 1000)
})
}

关于javascript - setTimeout 与 Promise 一起使用时的不明确行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53723172/

相关文章:

javascript - 为什么我不能内联调用 res.json?

javascript - 无法让 Angularjs promise 正常工作

javascript - react 。如何从父组件调用组件的方法

node.js - 使用 TypeORM 和 NestJs 和 Typescript 创建新迁移时出错

node.js - meteor在哪里安装packages.json中引用的npm包?

unit-testing - AngularJS : Need help to unit test a factory with promise

javascript - angularJS/breeze 删除 'intermediate' 负数条目(HTML5)

javascript - 是否可以使用 <img> 标签触发页面浏览?

javascript - Vimeo 视频播放完毕后,有什么方法可以关闭 Magnific?

node.js - Nodejs Rest API 与 mongoose 和 mongoDB