Reputation: 2578
I need to wait for all of the axios calls in a function called by a forEach loop to run before I call another function to reload data that should be updated by the axios calls.
function1() {
let arr = [1, 2, 3, 4, 5];
arr.forEach((num) => {
function2(num);
});
//Wait until each call in the forEach loop above
//is done before running the function3() function.
function3();
}
function2(number) {
axios.post('/internal-url/action/' + number)
.then((response) => {
return response;
});
}
function3() {
console.log('reloading data...');
/* DB call to reload data */
console.log('data is reloaded');
}
The problem here is that the data reloads before the axios calls are complete. I know the axios calls worked because I can see they updated in the database, but I need for function1()
to wait for all of the axios calls in function2()
to finish before running the reload in function3()
.
I've tried to make function1()
and function2()
async/await
functions, both at the same time and then individually, but that did not work. How would I go about doing this specifically?
Upvotes: 2
Views: 11300
Reputation: 63524
Create an array of promises then use Promise.all
to await their resolution/rejection using async/await
.
// async/await - create an array of promises
// from function2, then await until Promise.all has
// fully resolved/rejected
async function1() {
let arr = [1, 2, 3, 4, 5];
const promises = arr.map((num) => function2(num));
await Promise.all(promises);
function3();
}
function2(number) {
return axios.post('/internal-url/action/' + number);
}
function3() {
console.log('reloading data...');
/* DB call to reload data */
console.log('data is reloaded');
}
Upvotes: 6
Reputation: 791
Maybe like this:
const arr = [1, 2, 3, 4, 5];
let index = 0;
const answers = [];
(function loop() {
const value = arr[index];
function2(value).then(res => {
answers.push(res);
});
index++;
if (index < arr.length) {
loop();
}
})();
function3();
console.log(answers);
Upvotes: 1
Reputation: 503
The best solution would be to use Promise.all
so all the requests can be made in parallel. This would look something like this.
function1() {
let arr = [1, 2, 3, 4, 5];
Promise.all(arr.map((num) => function2(num))).then(() => {
function3();
});
}
This will wait until all of the promises that function2
returned have been resolved before calling function3
.
Upvotes: 2