[英]Multiple Http requests called and stored in one array, but how to wait until all requests finish before working with array
I have a array of values I want to loop over. 我有一个要遍历的值数组。 Each of these values will be used to make an http request to a server.
这些值中的每一个都将用于向服务器发出http请求。 From the server I will recieve a response for each request.
从服务器,我将收到每个请求的响应。 I want to store all these responses in a single array and then do work on the array once ALL requests have finished.
我想将所有这些响应存储在单个数组中,然后在所有请求完成后在数组上进行工作。 Due to the async nature of my code I am not sure how to make the application wait until all the requests have finished.
由于我代码的异步性质,我不确定如何使应用程序等待所有请求完成。 What is happening is I am making the requests, but the work I want to do with the array is already starting before ALL the requests have finished due to the async nature.
发生的事情是我在发出请求,但是由于异步的性质,我要对数组进行的工作已经在所有请求完成之前开始。 How can I make this code "synchronous" in the sence it waits until all requests have finished before starting to do the work with the listOfResponses array
我如何才能使此代码“同步”,使其等待所有请求完成之后才能开始使用listOfResponses数组进行工作
//import the require library to make http requests to a server
const request = require('request');
//values to be sent via a restful GET request
const list = [
'value_one',
'value_two'
];
//store resoonses from GET request
var listOfResponses = [];
//loop through the list
list.forEach(function(word) {
//Make a rest GET call to a server
var url = 'http://notsurehowtomakethisworksoiamaskingstackoverflow.com/api/words/' + word;
request(url, {
json: true
}, (err, res, body) => {
if (err) {
return console.log(err);
}
//store the response from the server into out array
listOfResponses.push(body.response);
});
});
/* *******************************
HERE I WANT TO DO STUFF WITH listOfResponses ONCE ALL THE REQUESTS FINISH
********************************** */
Just map it to an array of promises: 只需将其映射到一个promise数组即可:
const promises = list.map(word => new Promise(resolve => {
var url = 'http://notsurehowtomakethisworksoiamaskingstackoverflow.com/api/words/' + word;
request(url, {
json: true
}, (err, res) => {
if (err) {
return reject(err);
}
resolve(res.body);
});
}));
Then you can get all the results using Promise.all
: 然后,您可以使用
Promise.all
获得所有结果:
Promise.all(promises).then(results => {
//...
});
Simply check the responses each time a request ends: 每次请求结束时,只需检查响应即可:
//import the require library to make http requests to a server
const request = require('request');
//values to be sent via a restful GET request
const list = [
'value_one',
'value_two'
];
//store resoonses from GET request
var listOfResponses = [];
//loop through the list
list.forEach(function(word) {
//Make a rest GET call to a server
var url = 'http://notsurehowtomakethisworksoiamaskingstackoverflow.com/api/words/' + word;
request(url, {
json: true
}, (err, res, body) => {
if (err) {
return console.log(err);
}
//store the response from the server into out array
listOfResponses.push(body.response);
check();
});
});
// CHECK THE LIST
function check() {
if (listOfResponses.length == list.length) {
console.log("YAY! Here you have your responses", listOfResponses);
}
}
This is an asynchronous scenario, a way to accomplish that is calling recursively a function that will loop over your list
of words. 这是一个异步方案,一种实现方法是递归调用一个将遍历单词
list
的函数。 The recursion works according to each response from your server. 递归根据服务器的每个响应来工作。
Another approach is using Promise . 另一种方法是使用Promise 。
Look this code snippet (Recursion approach): 查看以下代码片段(递归方法):
//import the require library to make http requests to a server
const request = require('request');
//values to be sent via a restful GET request
const list = [
'value_one',
'value_two'
];
//store resoonses from GET request
var listOfResponses = [];
//loop through the list
var loop = function(array, index, cb) {
if (index === array.length)
cb();
return;
//Make a rest GET call to a server
var url = 'http://notsurehowtomakethisworksoiamaskingstackoverflow.com/api/words/' + array[i];
request(url, {
json: true
}, (err, res, body) => {
if (err) {
return console.log(err);
}
//store the response from the server into out array
listOfResponses.push(body.response);
loop(array, i++, cb);
});
};
loop(list, 0, function() {
/* *******************************
HERE I WANT TO DO STUFF WITH listOfResponses ONCE ALL THE REQUESTS FINISH
********************************** */
});
As you can see, the loop starts with a call to loop
function with index = 0
and every response will call the loop
function with an incremented index. 如您所见,循环从
index = 0
loop
函数调用开始,每个响应都将以递增的索引调用loop
函数。
The recursion ends when index == list.length
and the callback is executed to keep the flow of your logic. 当
index == list.length
时,递归结束,并且执行回调以保持逻辑流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.