如何将异步函数推送到数组而不执行未来的 Promise.all

Dan*_*l D 2 javascript arrays asynchronous promise

我有一些异步函数可以调用 REST API 并返回结果。我想使用 Promise.all 一次调用其中几个函数并等待完整结果。我了解 Promise.all 的工作原理,这不是 Promise.all 的问题。这是使用 Array.push 动态创建我想要调用的异步函数数组的问题。

所以这是场景。我的应用程序的用户加载了一个页面。该页面需要从 API 检索数据。它使用我提到的那些异步函数来做到这一点。但是,页面需要检索的数据根据​​设置的参数而有所不同。所以有时,它可能需要检索用户列表、特定客户和特定项目。其他时候,它可能需要获得所有用户和所有项目,而没有客户。

所以我的代码看起来像这样:

created() {
  let promiseList = []
  if (options.getCustomers) { promiseList.push(listCustomers())
  if (options.getCustomer) { promiseList.push(getCustomer(customerId)) }
  if (options.getUsers) { promiseList.push(getUsers()) }
  await Promise.all(promiseList)
}
Run Code Online (Sandbox Code Playgroud)

所以这在某种程度上是有效的。Promise.all 工作正常。问题是我不能在没有立即调用函数的情况下将函数推送到数组。因此,我推送到 promiseList 数组的每个函数都会被调用两次:一次又一次使用 Promise.all。

如何将异步函数作为引用推送到数组,以便它不会立即执行?

小智 6

将对该函数的引用放入数组中,然后在使用 Promise.all 时使用映射调用

created() {
  let promiseList = []
  if (options.getCustomers) { promiseList.push({ func: listCustomers })
  if (options.getCustomer) { promiseList.push({ func: getCustomer, arg: customerId}) }
  if (options.getUsers) { promiseList.push({ func: getUsers }) }
  await Promise.all(promiseList.map( (prom) => prom.func(prom.arg) ))
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不直接推送 `() => getCustomer(customerId)` 等等? (4认同)

Ome*_*mer 6

You can also push the function

created() {
     let promiseTasks = []; // meaning name is better
     if (options.getCustomers) {
         promiseTasks.push(() => listCustomers());
     }
     if (options.getCustomer) {
         promiseTasks.push(() => getCustomer(customerId));
     }
     if (options.getUsers) {
         promiseTasks.push(() => getUsers());
     }

     await Promise.all(promiseTasks.map((func) => func()));
 }
Run Code Online (Sandbox Code Playgroud)

Note: I don't think it's the use case you want to use Promise.all, because its looks like all get requests, and it's better to be separated to different endpoints.

Request option is useally can be options like: limit, sort, projection, populateQuery, preventPopulate.