首页 > 解决方案 > 如何为 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?

那是因为我仍然需要为每个“类型”(formvs responsepromises)保留所有这些结果的参考,而且我看不出在使用 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]));
    });

标签: javascriptarraysoptimizationpromiseasync-await

解决方案


 const [forms, responses] = await Promise.all([Promise.all(formsPromises), Promise.all(responsesPromises)]);

推荐阅读