如何在node.js中使用Promise.all和Request? [英] How to use Promise.all with Request in node.js?
问题描述
我想做的事情如下:
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....
});
上面是React.js代码,我想用Node做同样的事情。服务器上的js。问题是我没有提取,我有请求(我应该使用Request吗?)。 https://github.com/request/request
它以这种方式使用.. 。
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) {
});
但我如何使用Promise.all请求?因为我想获取多个东西并且只在Node完成所有操作时处理它们,而我宁愿不使用一堆回调。
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.
推荐答案
更简洁地说,在安装node-fetch之后,你可以做一个声明返回的fetch解析为json ...
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));
这篇关于如何在node.js中使用Promise.all和Request?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!