首页 > 解决方案 > 如何在不调用它们的情况下传递承诺数组?

问题描述

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

标签: javascriptpromiseaxioses6-promise

解决方案


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);

推荐阅读