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



我正在编写一个 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

在nodeJS中,你不做暂停,你使用它的异步性质来等待前面任务的结果,然后再继续下一个任务。

function callAPIs(id) {
  return new Promise((resolve, reject) => {
  // call some APIs and store the responses asynchronously, for example:
    request.get("https://example.com/api/?id=" + id, (err, response, body) => {
      if (err) {
        reject(err);
      }
      fs.writeFile(`./result/${id}/${id}_example.json`, body, err => {
        if (err) {
          reject(err);
        }
        resolve();
      });
    });
  });
}
for (let i = 1; i <= 4; i++) {
  await callAPIs(array[index], index, array);
}

此代码将执行请求,写入文件,一旦写入磁盘,它将处理下一个文件。

在处理下一个任务之前等待固定时间,如果需要更多时间怎么办?如果您浪费 3 秒钟只是为了确保它已完成怎么办?

您可能还想看看异步模块。它由async.times方法组成,它将帮助您实现所需的结果。

var fs = require('fs');
var request = require('request');
var async = require('async');

// run through the IDs
async.times(4, (id, next) => {
    // call some APIs and store the responses asynchronously, for example:
    request.get("https://example.com/api/?id=" + id, (err, response, body) => {
        if (err) {
            next(err, null);
        } else {
            fs.writeFile("./result/" + id + '/' + id + '_example.json', body, function (err) {
                if (err) {
                    next(err, null);
                } else
                    next(null, null);
            });
        }
    });
}, (err) => {
    if (err)
        throw err
});

您可以从以下共享网址中阅读有关它的信息:https://caolan.github.io/async/v3/docs.html#times

最新更新