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

Jon*_*Sud 2 javascript promise es6-promise axios

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

const arrayOfAxios = [
  axios('https://api.github.com/')
]

setTimeout(() => {
  console.log('before call promise');

  Promise.all(arrayOfAxios).then(res => {

   console.log({ res });
  });

}, 5000);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.js" integrity="sha256-bd8XIKzrtyJ1O5Sh3Xp3GiuMIzWC42ZekvrMMD4GxRg=" crossorigin="anonymous"></script>
Run Code Online (Sandbox Code Playgroud)

在我的代码中我可以https://api.github.com/立即看到这一点。而不是当我调用promise.all.

我做错了吗?还有另一种方法可以设置承诺数组并稍后调用它们吗?(我的意思是 axios 示例)

T.J*_*der 9

Promise 不运行任何东西,它们只是观察正在运行的东西。因此,并不是您不想调用承诺,而是您不想启动他们正在观察的事情。当您调用axios(或其他方式)时,它已经开始了它返回的承诺所观察到的过程。

\n\n

如果您不想启动该过程,请不要致电axios(等等)。例如,您可以在数组中放置一个调用它的函数,然后在准备好开始工作时调用它:

\n\n
const arrayOfAxios = [\n  () => axios('https://api.github.com/') // *** A function we haven't called yet\n];\n\nsetTimeout(() => {\n  console.log('before call promise');\n\n  Promise.all(arrayOfAxios.map(f => f())).then(res => {\n// \xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92^^^^^^^^ *** Calling the function(s)\n   console.log({ res });\n  });\n\n}, 5000);\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者,如果您对数组中的所有条目执行相同的操作,请存储该操作所需的信息(例如 的 URL 或选项对象axios):

\n\n
const arrayOfAxios = [\n  'https://api.github.com/' // *** Just the information needed for the call\n];\n\nsetTimeout(() => {\n  console.log('before call promise');\n\n  Promise.all(arrayOfAxios.map(url => axios(url))).then(res => {\n// \xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92^^^^^^^^^^^^^^^^^ *** Making the calls\n   console.log({ res });\n  });\n\n}, 5000);\n
Run Code Online (Sandbox Code Playgroud)\n