Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Pass anonymous functions to Promise.all

I'm trying to make multiple API calls concurrently using the Promise.all method with Axios, based on this example:

getUsers() { 
    return axios.get('/users');
}

getSessions() { 
    return axios.get('/sessions');
}

Promise.all([getUsers(), getSessions()])
    .then(results => {
      // Use the data
    })
    .catch(error => {
      // Catch the error
    });

However, as I will only know what concurrent API calls I need to make at this stage based on the result of a previous API call in the promise chain, I'm attempting to pass in an array of anonymous functions to the function in the form of:

var array = [];
array.push(() => {return axios.get('/users')}); 
array.push(() => {return axios.get('/sessions')});

Promise.all(array).then....

This doesn't work, and I understand that this is because I'm passing in function objects instead of referencing actual Promise objects as the method expects. However, pushing just axios.get(...) methods to the array results in them being called immediately, instead of later when the Promise.all method is executed.

I'm not sure how to do this properly, or whether there's a better approach to achieve what I'm after...

like image 596
user2521119 Avatar asked Dec 10 '22 07:12

user2521119


1 Answers

I am not familiar with Axios, but if I understand correctly axios.get returns a Promise, which you need for Promise.all. How about:

Promise.all(array.map(f => f()).then....

That way your functions are called when you actually want, and the map will give you an array of their results, so an array of Promises.

Note that this is essentially the same as the example you have cited with [getUsers(), getSessions()] – with the difference that your functions are anonymous and called implicitly using the map, instead of explicitly by their names. This way you have more flexibility in which functions actually get called.

like image 190
Aurel Bílý Avatar answered Dec 18 '22 07:12

Aurel Bílý