Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我如何在一个无限循环中使用承诺?_Javascript_Node.js_Asynchronous_Es6 Promise - Fatal编程技术网

Javascript 我如何在一个无限循环中使用承诺?

Javascript 我如何在一个无限循环中使用承诺?,javascript,node.js,asynchronous,es6-promise,Javascript,Node.js,Asynchronous,Es6 Promise,我需要以2000毫秒的延迟在无限循环中执行这段代码。我如何才能做到这一点?首先,停止每次执行都需要模块。让我们分别声明它们,这也将使代码更清晰易读: require("./getSongFromSpotify")().then(a => { require("./instify")(a.artist,a.name).then(r => { if (r.status === "ok"){

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

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

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)})
现在,让我们编写一个函数,在前一次执行完成和指定的计时器经过两秒钟后,我们将递归调用该函数:

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
}

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

使用
async
wait
语法,这看起来非常简单:

doJob();

您需要以2s延迟在无限循环中执行一些代码。那么这个问题和“承诺”有什么关系吗?我试过了,但没有得到任何答案output@tsh是的,当我在任何循环中执行这段代码时,它都不会等待结束承诺,但你不能保证承诺会在2秒内完成。对如果是的话。。。无论上一次执行已完成,您是否希望安排下一次执行?或者,如果上一次执行未完成,是否希望跳过下一次执行?或者您希望在上一次执行完成2秒后安排下一次执行,而不是在上一次执行开始后安排下一次执行?您可以在需要时说
。然后(doJob)
。然后(()=>doJob())。同时,你试图回报一个永远无法解决的承诺。它可能是无用的。@tsh作者要求无限循环,所以是的,在这个实现中它不会被解决。然而,我写道,作者可能需要有一个标志来指示是否应该解决作业,而不是运行下一个交互。
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);