I am having a NodeJS
project, where I have array of N parameters and I need to call an endpoint N times (once with each parameter). Then I need to listen once all the responses are returned and to execute a certain function only once all the results are retrieved.
I know how to implement the above in front-end frameworks, where I am using axios and then I am storing the responses from the axios in an array (for example responsePromises
) and then I am executing
return Promise.all(responsePromises).then(responses => { {
//do something with the responses[0], responses[1], etc...
}
So the above is something that I already use successfully. The issue is, now I need to do the same in my back-end (which I mentioned is a NodeJS
project).
Below is given the code that I am using for retrieving the data from a single endpoint and on success, I am executing the successMethod
.
let paramArray = ["one", "two", "three"];
let parsedURL = url.parse("https://this-is-my-url.com?param=" + paramArray[0]);
let proto = reqUrl.indexOf('https://') === 0 ? https : http;
let request = proto.get({
hostname: parsedURL.hostname,
port: parsedURL.port,
path: parsedURL.path
}, (response) => {
//do something on success
successMethod();
})
request.on('error', (e) => {
//do something on error
errorMethod();
});
request.end();
What I am not sure is, how to apply the implementation with Promise.all
inside of the NodeJS
code which I am using? Would be ideal if I can somehow loop through the paramArray
array again, to store the promises into another responsePromises
array and to execute my successMethod only when I have all the responses returned.
This was the solution to my problem: