How to use Promise.all with Request in node.js?

2019-06-04 05:38发布

问题:

I'd like to do something along the lines of:

Promise.all([
    fetch(url1).then(function(response){ return response.json() }),
        fetch(url2).then(function(response){ return response.json() }),
            fetch(url3).then(function(response){ return response.json() }),
                fetch(url4).then(function(response){ return response.json() })
    ]).then(allResponses => {

    var data1 = allResponses[0];
    var data2 = allResponses[1];
    var data3 = allResponses[2];
    var data4 = allResponses[3];

    // process data....

    });

The above is React.js code, I'd like to do the same thing but with Node.js on the server. Problem is I don't have fetch, I have request (should I even be using Request?). https://github.com/request/request It's used in this way...

var request = require('request');

request(url1, function (error, response, body) {
});

But how would I use request with Promise.all? Because I want to fetch multiple things and only process them when all are done but in Node, and I'd rather not use a bunch of callbacks.

回答1:

More concisely, after installing node-fetch, you can make a promise-returning fetch that resolves to json...

const fetch = require('node-fetch');
function fetchJSON(url) {
    return fetch(url).then(response => response.json());
}

...build an array of promises from an array of urls...

let urls = [url1, url2, url3, url4];
let promises = urls.map(url => fetchJSON(url));

...do something when those promises resolve...

Promise.all(promises).then(responses => console.log(responses));


回答2:

Convert the requests into promises:

function promiseRequest(url) {
  return new Promise(resolve => {
    request(url, function(err, response, body) {
      resolve(body);
    });
  });
}

Then you can do something like

const allBodies = await Promise.all([
  promiseRequest(url1),
  promiseRequest(url2),
  promiseRequest(url3)
]);

But it would be nicer to use fetch natively.



回答3:

I just did

npm install node-fetch

and then

var fetch = require('node-fetch');

and then I could use my code above, ie

Promise.all([
    fetch(url1).then(function(response){ return response.json() }),
        fetch(url2).then(function(response){ return response.json() }),
            fetch(url3).then(function(response){ return response.json() }),
                fetch(url4).then(function(response){ return response.json() })
    ]).then(allResponses => {

    var data1 = allResponses[0];
    var data2 = allResponses[1];
    var data3 = allResponses[2];
    var data4 = allResponses[3];

    // process data....

    });