javascript - 如何在延迟的无限循环中使用承诺?
问题描述
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');
现在让我们编写一个函数,我们将在前一次执行完成和承诺的计时器经过两秒后递归调用该函数:
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();
请注意,这种方法将导致无限循环(如您所要求的),但我认为您可能需要设置一些额外的变量/标志,这些变量/标志将在每次迭代之前进行检查,以便能够停止它。
推荐阅读
- ruby-on-rails - 无法在 Rails 应用程序中刷新 Google API 令牌
- python - 从 cython 调用 c++ 模板函数
- c - 为什么添加 char(来自 argv)会导致 C 中没有结果
- angular - 量角器 - 在 pdf 查看器 iframe 中找不到下载按钮
- php - 如何对一组关联数组进行分组并声明自定义键?
- python - 蟒蛇基维。我的程序应该附加文本文件,但不是
- microsoft-dynamics - Dynamics 365 javascript 验证器
- python - Have 子句中的 SQLAlchemy 引用标签
- azure - 模拟数据 Cosmosdb
- android - 无法输入编辑文本 (android.support.v7.widget.AppCompatEditText)