Search code examples
javascriptpromiseaxioses6-promise

How to pass array of promise without invoke them?


I try to pass array of axios (as promise) to a function. and when I call the method I need to execute those promises.

const arrayOfAxios = [
  axios('https://api.github.com/')
]

setTimeout(() => {
  console.log('before call promise');

  Promise.all(arrayOfAxios).then(res => {

   console.log({ res });
  });

}, 5000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.js" integrity="sha256-bd8XIKzrtyJ1O5Sh3Xp3GiuMIzWC42ZekvrMMD4GxRg=" crossorigin="anonymous"></script>

In my code I can see that https://api.github.com/ immediately. and not when I invoke the promise.all.

Did I do it wrong? there is another way to set array of promises and invoke them later? (I mean for an axios example)


Solution

  • Promises don't run anything, they just observe things that are running. So it's not that you don't want to invoke the promises, it's that you don't want to start the things they're observing. When you call axios (or whatever), it's already started its process that the promise it returns observes.

    If you don't want that process to start, don't call axios (etc.). For instance, you might put a function that calls it in the array instead, then call it when you're ready for it to start its work:

    const arrayOfAxios = [
      () => axios('https://api.github.com/') // *** A function we haven't called yet
    ];
    
    setTimeout(() => {
      console.log('before call promise');
    
      Promise.all(arrayOfAxios.map(f => f())).then(res => {
    // −−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^ *** Calling the function(s)
       console.log({ res });
      });
    
    }, 5000);
    

    Or if you're doing the same operation on all of the entries in the array, store the information needed for that operation (such as the URLs or options objects for axios):

    const arrayOfAxios = [
      'https://api.github.com/' // *** Just the information needed for the call
    ];
    
    setTimeout(() => {
      console.log('before call promise');
    
      Promise.all(arrayOfAxios.map(url => axios(url))).then(res => {
    // −−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^ *** Making the calls
       console.log({ res });
      });
    
    }, 5000);