I have a function that returns a promise. In the function I cycle through an array and make a request using the request module for each element in the array.
I'd like to resolve the promise once I've gotten a response for each request. Right now I've managed to do that by creating a count variable and resolving once the count reaches the same length as the array. This doesn't seem like a strong/tenable option. Is there another way I can wait to resolve until after the last request callback has fired`
function getSens(arr) {
return new Promise(function(resolve, reject) {
var count = 0;
arr.forEach(function(a) {
var data = postData;
request.post({
headers: { 'content-type': 'application/x-www-form-urlencoded' },
url: apiEndpoint',
body: data
}, function(error, response, body) {
count++;
if (!error && response.statusCode == 200) {
let data = JSON.parse(body);
a['apiResponse'] = data;
}
if (count === a.length) {
resolve(ad);
}
});
});
});
}
`