0

I want to send a dynamic amount ajax requests at same time and want a callback to them all (i.e. the callback to the last one returning), but I am using node.js. I found a jquery version to solve it here Pass in an array of Deferreds to $.when() but how can I do this in node.js?

Thanks

Community
  • 1
  • 1
omega
  • 40,311
  • 81
  • 251
  • 474

2 Answers2

0

Promise.all takes an array of promises and returns a Promise of Array. The node-fetch module can be used to make HTTP requests asynchronously (AJAX only really refers to browser-executed requests.)

Bluebird is a nodejs Promise polyfill.

Something like

var fetch = require('node-fetch'),
    Promise = require('bluebird');

function fetchUrls(URLs) {
    return Promise.all(URLs.map(function (URL) {
        return fetch(URL).then(function (response) {
            return response.json();
        });
    }));
}

fetchUrls(['url1','url2']).then(function (data) {
    // do stuff with the result data here
});
George Simms
  • 3,930
  • 4
  • 21
  • 35
0

NodeJS doesn't use AJAX, you have the HTTP API or request. What you're trying to do can be solved with either Promises or the async library.

One way of solving the problem is this (untested):

   var async = require("async");
   var request = require("request");
   async.map(["https://target.com/a","https://target.com/b"], request, function (err, data) {
      console.log(data);
   });
Lorenz
  • 2,179
  • 3
  • 19
  • 18