Skip to content Skip to sidebar Skip to footer

How To Make A Synchronous Delay Inside A For Loop?

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

Solution 1:

You can use the new ES6's async/await

(async () => {
    for(var i = 1; i <= 4; i++)
    {
        console.log(`Calling API(${i})`)
        awaitcallAPIs(i);
        console.log(`Done API(${i})`)
    }
})();

functioncallAPIs(id)
{
    returnnewPromise(resolve => {
        // Simulating your network request delaysetTimeout(() => {
            // Do your network success handler function or other stuffreturnresolve(1)
        }, 2 * 1000)
    });
}

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

Solution 2:

In nodeJS you don't do pauses, you use it's asynchronous nature to await the result of preceding tasks, before resuming on next task.

functioncallAPIs(id) {
  returnnewPromise((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++) {
  awaitcallAPIs(array[index], index, array);
}

This code, will do request, write the file, and once it is written to disk, it will process the next file.

Waiting a fixed time before the next task is processed, what if would take a bit more time? What if you're wasting 3 seconds just to be sure it was done...?

Solution 3:

You might also want to have a look at the async module. It consists of async.times method which will help you achieve the results you need.

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


// run through the IDsasync.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);
                } elsenext(null, null);
            });
        }
    });
}, (err) => {
    if (err)
        throw err
});

You can read about it from the below shared url: https://caolan.github.io/async/v3/docs.html#times

Post a Comment for "How To Make A Synchronous Delay Inside A For Loop?"