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

How to make a synchronous delay inside a for loop?

我正在编写一个 NodeJS 脚本,它通过 GET(使用来自 npm 的 request)调用一堆 API,并将响应保存在 JSON 文件中。我正在使用 for 遍历 ID 以传递给 APIs,但我无法在呼叫突发之间设置延迟,因此我不会向 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

在 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 秒只是为了确定它已完成怎么办...?

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

您可能还想看看异步模块。它包含 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
});

您可以从下面的分享中了解它url: https://caolan.github.io/async/v3/docs.html#times