如何在不调用它们的情况下传递承诺数组?

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="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(或其他任何方式)时,它 已经 开始了它 returns 遵守的承诺的过程。

如果您不想启动该进程,请不要调用 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);