首页 > 解决方案 > 如何在延迟的无限循环中使用承诺?

问题描述

require("./getSongFromSpotify")().then(a => {
    require("./instify")(a.artist,a.name).then(r => {
        if (r.status === "ok"){
            console.log("saved")
        }else{
            console.log("Instagram API have a problem!")
        }
    }).catch((r) => {console.error(r)})
}).catch((r) => {console.error(r)})

我需要以 2000 毫秒的延迟在无限循环中执行此代码。我怎样才能做到这一点?

标签: javascriptnode.jsasynchronouses6-promise

解决方案


首先,停止每次执行都需要模块。让我们分别声明它们,这也将使代码更加清晰易读:

const getSong = require('./getSongFrompotify');
const instify = require('./instify');

现在让我们编写一个函数,我们将在前一次执行完成和承诺的计时器经过两秒后递归调用该函数:

function waitFor(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  })
}

function doJob() {
  return getSong()
    .then(song => instify(song.artist, song.name))
    .then(result => {
      if (result.status === 'ok') {
        console.log('saved');
      } else {
        console.log('Problem!');
      }
    }) // no need to have 2 separate 'catch'
    .catch(err => console.error(err)) // all errors fall here
    .finally(() => waitFor(2000)) // anyway wait 2 seconds
    .then(() => doJob()); // and run all again
}

现在,我们只需要调用它:

doJob();

请注意,这种方法将导致无限循环(如您所要求的),但我认为您可能需要设置一些额外的变量/标志,这些变量/标志将在每次迭代之前进行检查,以便能够停止它。


推荐阅读