javascript - 如何在不调用它们的情况下传递承诺数组?
问题描述
我尝试将 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 的例子)
解决方案
Promise 不会运行任何东西,它们只是观察正在运行的东西。所以不是你不想调用承诺,而是你不想开始他们正在观察的事情。当您调用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);
或者,如果您对数组中的所有条目执行相同的操作,请存储该操作所需的信息(例如 的 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);
推荐阅读
- android - 如何在列表视图中仅显示选定的记录?
- redirect - Laravel 5.5 $redirectTo 在 2 次修改后没有改变
- javascript - NestJs:如何在实体监听器中访问数据库?
- reactjs - 更新更高父组件中的子状态
- sql - 当文件结构发生变化时,如何在 SQL 中解析 XML?
- c# - 为什么静态构造函数的顺序是这样的 C#?
- regex - 如何在Jmeter中将正则表达式提取器输出保存在文件(csv或任何其他格式)中
- php - 我想制作两个按钮,一个最大化,另一个最小化浏览器页面的大小
- python - Python CSV writerow 到已打开文件中的特定列
- php - 如何使用日期在 PHP 中获取日期的名称?