How to use $.when in node.js? [duplicate]

617
November 23, 2016, at 9:36 PM

This question already has an answer here:

  • Native Support for Promises in Node.js 8 answers

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

Answer 1

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

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
});
READ ALSO
Add node to Tree

Add node to Tree

I decided to use nested sets model. [nnn]My table has columns: id, name, lft, rgt, parent_id.

677
javascript/jquery: on click copy relevant array items to new array

javascript/jquery: on click copy relevant array items to new array

I think I'm missing an obvious answer. I have an array of arrays, like this.

644
Convert datetime with Jquery

Convert datetime with Jquery

Well, i'm modifying a board system, and i have this datetime format:.

494