0

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);
                }
            });
        });
    });
}

`

  • Look into `Promise.all()`. It could look something like `Promise.all(arr.map(a => {return new Promise((res, rej) => {/*make request*/})})).then(()=>{/*all requests done*/})` – E. Sundin Jul 09 '17 at 01:41
  • A bunch of different options here: [How can I wait for set of asynchronous callback functions?](https://stackoverflow.com/questions/10004112/how-can-i-wait-for-set-of-asynchronous-callback-functions/10004137#10004137). The promise-based solution is usually to promisify the underlying operation and then use `Promise.all()` to be notified when all the underlying promises are done. FYI, a counter can be made to work (that's what `Promise.all()` uses internally), but it is work to get the error handling correct and get all the responses in order, both of which your current code seems to ignore. – jfriend00 Jul 09 '17 at 01:42

0 Answers0