Reputation: 129
I have three arrays:
const firstArray = ['a', 'b', 'c']
const secondArray = ['i', 'j', 'k']
const thirdArray = ['x', 'y', 'z']
I have to send multiple requests using all possible combinations and wait for all the responses to be resolved before continuing. So I tried to do it like this
const getPromises = () => {
const promises = firstArray.map(first => {
return secondArray.map(second => {
return thirdArray.map(third => {
return axios.get(`https://someurl.com/${first}/${second}/${third}`)
.then(response => response);
})
})
})
return Promise.all(promises)
}
And I have another method where I tried to get returned values from this method
const getvalues = async () => {
const someVariable = await getPromises();
}
But it didn't work out. Variable someVariable
just had unresolved promises.
What I did wrong?
Upvotes: 1
Views: 109
Reputation: 467
I'd do it like this:
const getPromises = () => Promise.all(function* () {
for (let first of firstArray)
for (let second of secondArray)
for (let third of thirdArray)
yield axios.get(`https://someurl.com/${first}/${second}/${third}`)
}());
Upvotes: 2
Reputation: 1948
Approaching to solve your problem with .map
doesn't work, because nested map-functions are returning nested arrays and Promise.all
expects an array of promises as entries not arrays itself.
The best approach might be using nested for...of
loops:
const firstArray = ['a', 'b', 'c'];
const secondArray = ['i', 'j', 'k'];
const thirdArray = ['x', 'y', 'z'];
const getPromises = () => {
const promises = [];
for (let first of firstArray )
for (let second of secondArray)
for (let third of thirdArray ) {
promises.push(axios.get(`https://someurl.com/${first}/${second}/${third}`));
}
return Promise.all(promises);
};
Upvotes: 1
Reputation: 4037
Here is an example that shows what you need:
const a = ['a', 'b', 'c'];
const b = ['i', 'j', 'k'];
const c = ['x', 'y', 'z'];
let promises = [];
a.forEach((i1) => {
b.forEach((i2) => {
c.forEach((i3) => {
let promise = new Promise((res, rej) => {
setTimeout(function() {
res([i1, i2, i3])
}, 250)
}).then(([j1, j2, j3]) => console.log(j1, j2, j3));
promises.push(promise);
})
})
});
Promise.all(promises).then(() => console.log("finish"));
Just replace the setTimeout
with your axios.get(https://someurl.com/${first}/${second}/${third})
Upvotes: 0