Mark Tyers Mark Tyers - 1 year ago 78
Node.js Question

Looping through functions containing callbacks

I am trying to use NodeJS 6.3.1 repeat a similar async function to access paged data. The aim is to calculate the number of pages of data based on the total rows and the rows per page then call the API to retrieve each page of data using the request package.

For example if there were 34 rows in total with 10 records per page I would need to call each of the following URLs.

Given each of these calls requires a callback, how can I iterate through them?

Answer Source

Here is how you can use Promise.all():

// This is will be your get request function
function getRequest(url) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
    }, 2000);

var promises = [];
var url = '';

for (var i = 1; i < 10; i++) {
  // Creating a list of promises (get requests)
  promises.push(getRequest(url + i));

// After all of the promises have resolved, all of the responses will be
// concatinated into a list of responses and passed in like this:
Promise.all(promises).then(function(allResponses) {


If you are using the default node request the getRequest() method will look something like this:

var request = require('request');

function getRequest(url) {
  return new Promise(function(resolve, reject) {
    request(url, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        resolve(body); // or resolve(response) if that is what you are looking for
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download