如何传递承诺数组而不调用它们? [英] How to pass array of promise without invoke them?

查看:23
本文介绍了如何传递承诺数组而不调用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将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示例)

推荐答案

承诺不会运行任何内容,它们只是观察正在运行的内容。所以不是你不想援引承诺,而是你不想开始他们正在观察的事情。当您调用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);

这篇关于如何传递承诺数组而不调用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆