我尝试将 axios 数组(如承诺)传递给函数。当我调用该方法时,我需要执行这些承诺。
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>
在我的代码中我可以看到https://api.github.com/
立即地。而不是当我调用promise.all
.
我做错了吗?还有另一种方法可以设置承诺数组并稍后调用它们吗? (我的意思是 axios 示例)
承诺却没有run任何事,他们只是observe正在运行的东西。因此,并不是您不想调用承诺,而是您不想启动他们正在观察的事情。你打电话时axios
(或其他什么),它是already开始它返回的承诺所观察到的过程。
如果您不想启动该过程,请不要致电axios
(ETC。)。例如,您可以在数组中放置一个调用它的函数,然后在准备好开始工作时调用它:
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);
或者,如果您对数组中的所有条目执行相同的操作,请存储该操作所需的信息(例如 URL 或选项对象)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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)