如何传递承诺数组而不调用它们?

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

相关文章