如何对promises数组进行promise.all,同时保留对这些数组的引用?

时间:2019-03-23 13:38:10

标签: javascript arrays optimization promise async-await

我有以下运行良好的代码,并且我希望通过一起运行所有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 array of promises?

那是因为我仍然需要针对每个“类型”(formresponse承诺)保留所有这些结果的引用,并且我看不到使用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]));
    });

1 个答案:

答案 0 :(得分:3)

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