How to pass array of promise without invoke them?(如何传递承诺数组而不调用它们?)
本文介绍了如何传递承诺数组而不调用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试将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="aHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS9hamF4L2xpYnMvYXhpb3MvMC4xOS4yL2F4aW9zLmpz" integrity="sha256-bd8XIKzrtyJ1O5Sh3Xp3GiuMIzWC42ZekvrMMD4GxRg=" crossorigin="anonymous"></script>
在我的代码中,我可以立即看到https://api.github.com/
。而不是在我调用promise.all
时。
我做错了吗?还有另一种方法可以设置承诺数组并在以后调用它们吗?(我指的是AXIOS示例)
推荐答案
承诺不会运行任何内容,它们只是观察正在运行的内容。所以不是你不想援引承诺,而是你不想开始他们正在观察的事情。当您调用axios
(或其他函数)时,已已开始它返回的承诺遵守的进程。
axios
(依此类推)。例如,您可以将调用它的函数放在数组中,然后在准备好开始工作时调用它:
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);
或者,如果您对数组中的所有条目执行相同的操作,请存储该操作所需的信息(例如axios
的URL或选项对象):
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);
这篇关于如何传递承诺数组而不调用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何传递承诺数组而不调用它们?


猜你喜欢
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01