如何在延迟的无限循环中使用 promises?

How can I use promises in an infinite loop with delay?

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 毫秒的无限循环中执行此代码。我该怎么做?

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

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

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

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();

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

使用 async await 语法,可以使这看起来非常简单:

const getSongFromSpotify = require("./getSongFromSpotify");
const instify = require("./instify");

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

async function keepPolling() {
    while (true) { // forever (or until rejection)
        let song = await getSongFromSpotify();
        let result = await instify(song.artist, song.name);
        if (result.status === "ok") {
            console.log("saved");
        } else {
            console.log("Instagram API has a problem!");
        }
        await delay(2000);
    }
}

keepPolling().catch(console.error);