如何在for循环内进行同步延迟? [英] How to make a synchronous delay inside a for loop?

查看:92
本文介绍了如何在for循环内进行同步延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 NodeJS 脚本,它通过 GET(使用来自 npm 的 request)调用一堆 API,并将响应保存在一个 JSON 文件中.我正在使用 for 循环遍历 ID 以传递给 API,但我无法在呼叫突发之间设置延迟,因此我不会向 API 服务器发送垃圾邮件并使其生气我(速率限制).有人知道怎么做吗?

我当前的代码(没有任何延迟):

var fs = require('fs');var request = require('request');//遍历 IDfor(var i = 1; i <= 4; i++){(功能(一){callAPIs(i);//调用我们的 API})(一世);}函数调用APIs(id){//调用一些 API 并异步存储响应,例如:request.get("https://example.com/api/?id=" + id, (err, response, body) =>{如果(错误){抛出错误;}fs.writeFile("./result/" + id + '/' + id + '_example.json', body, function (err){如果(错误){抛出错误;}});});}

我正在寻找这种行为:

callAPIs(1);//开始对 ID# 1 的呼叫突发//稍等一会...callAPIs(2);//开始对 ID# 2 的呼叫突发//稍等一会...//等等

解决方案

你可以使用新的 ES6 的 async/await

(async() => {for(var i = 1; i <= 4; i++){console.log(`调用 API(${i})`)等待 callAPIs(i);console.log(`Done API(${i})`)}})();函数调用APIs(id){返回新的承诺(解决 => {//模拟你的网络请求延迟setTimeout(() => {//做你的网络成功处理函数或其他东西返回解决(1)}, 2 * 1000)});}

一个工作演示:https://runkit.com/5d05476405c94a/5d05476405c95c95c94054040404054054040404040540404054040404054040405404040403

I'm writing a NodeJS script that calls a bunch of APIs via GET (using request from npm) and saves the responses in a JSON file. I'm using a for to loop through IDs to pass to the APIs, but I'm having trouble putting in a delay between call bursts so I don't spam the API server and make it mad at me (rate limiting). Does anyone know how to do this?

My current code (without any delay):

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

I'm looking for this behavior:

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

解决方案

You can use the new ES6's 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)
    });
}

A working demo: https://runkit.com/5d054715c94464001a79259a/5d0547154028940013de9e3c

这篇关于如何在for循环内进行同步延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆