javascript - 如何为 promise 数组执行 promise.all,但保留对这些数组的引用?
问题描述
我的以下代码运行良好,我希望通过一起运行所有 Promise 来进一步提高性能,而不是一个接一个地运行两个 Promise 数组。
在以下源代码的以下片段中:
const forms = await Promise.all(formsPromises);
const responses = await Promise.all(responsesPromises);
在这里,我首先运行一个数组formsPromises
(它们本身彼此并行运行),一旦结束,我运行另一个数组responsesPromises
. 我想知道如何并行运行它们(responsesPromises
不应该等待formsPromises
完成)
我研究了其他类似的问题,但没有找到合适的方法,比如How to do promise.all for array of promises?
那是因为我仍然需要为每个“类型”(form
vs response
promises)保留所有这些结果的参考,而且我看不出在使用 reduce 等技术时这是如何实现的。
const formsPromises = []; // Will contain Promises
const responsesPromises = []; // Will contain Promises
const results = { // Define initial shape of the results (which is what we should get from the API if there were no results)
items: [],
answersCsv: [],
total_items: 0,
page_count: 0,
avg_elapsed_seconds: 0,
};
const computedResults = []; // Used to calculate statistic data based on all responses
// XXX Run all promises in parallel
map(parameters.form_ids_cleaned, (form_id) => {
// Fetch the form data, necessary during computing in order to resolve refs for multi choices questions
formsPromises.push(typeformAPI.forms.get({ uid: form_id }));
// Fetch the responses for the form
// XXX This will perform a recursive call under the hood if there are many results and no results limit is defined
responsesPromises.push(fetchFormResponses({
parameters,
queryStringParameters: event.queryStringParameters,
typeFormApiParameters: {
...typeFormApiParameters,
uid: form_id,
},
typeformAPI,
}));
});
// ------ HERE ---------
const forms = await Promise.all(formsPromises);
const responses = await Promise.all(responsesPromises);
map(responses, (response, index) => {
// Compute results for each set of responses (per form), which will bind CSV-friendly fields and computed statistic data
computedResults.push(computeResults(response, forms[index]));
});
解决方案
const [forms, responses] = await Promise.all([Promise.all(formsPromises), Promise.all(responsesPromises)]);
推荐阅读
- r - 从 BoomSpikeSlab 模型中提取包含概率和正概率
- azure-active-directory - 为什么 Azure B2C 在尝试登录时找不到所有者帐户
- javascript - 侧边栏粘着 Javascript 代码?
- javascript - 如何在测试之间传递可变数据
- javascript - 确保变量是数组
- makefile - 有没有一种规范的方法来获取 Make 规则中的前 n 个依赖项?
- php - GAE 上的自动完成功能未从 search.php 文件加载 JSON
- php - 如何通过消息 ID 使用 PHP imap_search()
- python - NameError:名称“构建”未定义
- ios - 如何限制文本字段中的数字范围(swift4)