我有一些异步函数,它们调用REST并返回结果。我想使用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)
}所以这在某种程度上是可行的。Promise.all工作得很好。问题是,如果不立即调用函数,就无法将函数推送到数组中。因此,我要推送到promiseList数组的每个函数都会被调用两次:立即调用,然后再使用Promise.all调用。
如何将异步函数作为引用推送到数组,使其不会立即执行?
发布于 2020-02-20 18:46:27
将对函数的引用放入数组中,然后在使用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) ))
}发布于 2021-03-30 08:54:26
您也可以推送该函数。
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()));
}注意:我不认为这是您想要使用Promise.all的用例,因为它看起来像所有的get请求,最好分离到不同的端点。请求选项通常可以是这样的选项:限制、排序、投影、populateQuery、preventPopulate.
https://stackoverflow.com/questions/60326609
复制相似问题