如何在不调用诺言的情况下传递诺言?

我尝试将axios数组(按承诺)传递给函数。当我调用该方法时,我需要执行那些promise。

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示例)

tf2818715 回答:如何在不调用诺言的情况下传递诺言?

承诺不会运行任何东西,它们只是观察正在运行的东西。因此,这并不是说您不想调用诺言,而是您不想启动它们正在观察的事情。当您致电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);
本文链接:https://www.f2er.com/2653519.html

大家都在问