Ross Coundon
Ross Coundon

Reputation: 917

Building a Promise array doesn't work but single promises do

I have a loop that calls a function that resolves a Promise and I need to call that multiple times. When all calls have completed I then want to process all the promises' results.

I have an odd situation where if I take the call out of the loop, the Promise resolves and I can work with it in my Promise.all block. But, if instead I call the function multiple times and .push into an array, I get an array of correct size but with no objects inside.

This without the loop works and I can see data in the geocodeResult object:

var geocodePromise = geocodeRows(parsed.data[0]);
Promise.all([geocodePromise]).then(function([geocodeResult]) {
    console.log("IN PROMISE: " + beautify(geocodeResult, null, 2, 80));
})
.catch(function (error) {
    console.log("Error: " + error);
})
.catch(function () {
    console.log("Error");
}); 

However, with a loop of calls:

var geocodeStack = [];
for(j=0; j<parsed.data.length; j++){
    geocodeStack.push(geocodeRows(parsed.data[j]));
}
console.log(beautify(geocodeStack, null, 2, 80));

Promise.all([geocodeStack]).then(function([geocodeResult]) {
    console.log("IN PROMISE: " + beautify(geocodeResult, null, 2, 80));
})
.catch(function (error) {
    console.log("Error: " + error);
})
.catch(function () {
    console.log("Error");
});

The console output looks like this:

IN PROMISE: [ {}, {} ] 

Can anyone tell me what I'm doing wrong?

Upvotes: 0

Views: 50

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

I think you need Promise.all([...geocodeStack]) or Promise.all(geocodeStack).

You mixed two approaches and got Promise.all([geocodeStack]) which passes an array of array into your Promise.all, not an array of Promises.

Upvotes: 3

Related Questions