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

时间:2019-06-15 19:27:26

标签: javascript node.js synchronous

我正在编写一个NodeJS脚本,该脚本通过GET(使用npm的res5 = '(?-i:TeSt)' )调用GET,并将响应保存在JSON文件中。我正在使用request来循环通过ID传递给API,但是我无法在两次通话之间设置延迟,因此我不会向API服务器发送垃圾邮件,并且会生气限制)。有谁知道该怎么做?

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

for

我正在寻找这种行为:

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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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

答案 2 :(得分:0)

您可能还想看看异步模块。它由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