【问题标题】:How to pass array of promise without invoke them?如何在不调用它们的情况下传递承诺数组?
【发布时间】:2020-06-25 05:47:53
【问题描述】:

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

【问题讨论】:

  • 承诺已经执行。您不会先创建一个 Promise 对象,然后再“启动”它。这个过程是你首先启动一个异步操作,然后你得到一个 Promise。
  • 为什么不只传递 url?并在你想要的时候执行它们......

标签: javascript promise axios es6-promise


【解决方案1】:

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

或者,如果您对数组中的所有条目执行相同的操作,请存储该操作所需的信息(例如 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 2020-02-17
    • 2016-06-16
    • 2016-12-13
    相关资源
    最近更新 更多