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('/')
]
setTimeout(() => {
console.log('before call promise');
Promise.all(arrayOfAxios).then(res => {
console.log({ res });
});
}, 5000);
<script src=".19.2/axios.js" integrity="sha256-bd8XIKzrtyJ1O5Sh3Xp3GiuMIzWC42ZekvrMMD4GxRg=" crossorigin="anonymous"></script>
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./')
]
setTimeout(() => {
console.log('before call promise');
Promise.all(arrayOfAxios).then(res => {
console.log({ res });
});
}, 5000);
<script src="https://cdnjs.cloudflare./ajax/libs/axios/0.19.2/axios.js" integrity="sha256-bd8XIKzrtyJ1O5Sh3Xp3GiuMIzWC42ZekvrMMD4GxRg=" crossorigin="anonymous"></script>
In my code I can see that https://api.github./
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)
Share Improve this question asked Mar 13, 2020 at 7:41 Jon SudJon Sud 11.8k31 gold badges104 silver badges228 bronze badges 2- Promises are already executed. You don't first create a Promise object and then "start" it. The process is that you first start an async operation, then you get a Promise. – VLAZ Commented Mar 13, 2020 at 7:43
- 1 Why not just passing urls? and executing them when you want... – V. Sambor Commented Mar 13, 2020 at 7:44
1 Answer
Reset to default 11Promises 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./') // *** 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./' // *** 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);