我正在编写一个 NodeJS 脚本,它通过 GET 调用一堆 API(使用request
来自 npm)并将响应保存在 JSON 文件中。我正在使用一个for
循环遍历ID以传递给API,但是我在调用突发之间设置延迟时遇到了麻烦,这样我就不会向API服务器发送垃圾邮件并让它生我的气(速率限制)。有谁知道如何做到这一点?
我当前的代码(没有任何延迟):
var fs = require('fs');
var request = require('request');
// run through the IDs
for(var i = 1; i <= 4; i++)
{
(function(i)
{
callAPIs(i); // call our APIs
})(i);
}
function callAPIs(id)
{
// call some APIs and store the responses asynchronously, for example:
request.get("https://example.com/api/?id=" + id, (err, response, body) =>
{
if (err)
{throw err;}
fs.writeFile("./result/" + id + '/' + id + '_example.json', body, function (err)
{
if (err)
{throw err;}
});
});
}
我正在寻找这种行为:
callAPIs(1); // start a burst of calls for ID# 1
// wait a bit...
callAPIs(2); // start a burst of calls for ID# 2
// wait a bit...
// etc
您可以使用新的 ES6async/await
(async () => {
for(var i = 1; i <= 4; i++)
{
console.log(`Calling API(${i})`)
await callAPIs(i);
console.log(`Done API(${i})`)
}
})();
function callAPIs(id)
{
return new Promise(resolve => {
// Simulating your network request delay
setTimeout(() => {
// Do your network success handler function or other stuff
return resolve(1)
}, 2 * 1000)
});
}
一个工作演示:https://runkit.com/5d054715c94464001a79259a/5d0547154028940013de9e3c https://runkit.com/5d054715c94464001a79259a/5d0547154028940013de9e3c
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)