gpt4 book ai didi

javascript - 如何在for循环内进行同步延迟?

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:50 25 4
gpt4 key购买 nike

我正在编写一个 NodeJS 脚本,该脚本通过 GET 调用一堆 API(使用来自 npm 的 request)并将响应保存在 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

最佳答案

您可以使用新的 ES6 的 async/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

关于javascript - 如何在for循环内进行同步延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56613559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com