Promises.all在函数返回之前没有完成

时间:2016-09-06 18:45:23

标签: javascript promise

我已经和我搏斗了一下,我不确定下一步。我试图在switch语句中进行异步数据库调用。现在,我知道如果我把它放在语句中,它就不会及时履行承诺,所以我已经创建了一个调用数组,并且在构建返回的对象之前尝试解决它们。现在,我只是返回failed_tests的空数组,因为Promise.all在构建对象之前并未完成。

function getMetrics(num_tests, env)
{
  return new Promise((fulfill, reject) =>
  {
    elastic.getMostRecentResults(num_tests, env).then(results =>
    {
      var promises = [];
      var num_failed = 0,
          num_passes = 0,
          num_skipped = 0,
          failed_tests = [];
      results.aggregations.tests.buckets.forEach(bucket =>
      {
        switch(bucket.most_recent_result.hits.hits[0]._source.status)
        {
          case "passed":
            num_passes++;
            break;

          case "skipped":
            num_skipped++;
            break;

          case "failed":
            num_failed++;
            var full_id = bucket.most_recent_result.hits.hits[0]._source.full_id;
            promises.push(getResultsForFailedTest(full_id, env));

            break;

          default:
            break;
        }
      });

      console.log(promises.length);

      Promise.all(promises).then(results => {
        failed_tests.push(results)
      }).catch(err => {
        console.log(err)
      });

      var metrics = {
        "total_tests": num_tests,
        "num_pass": num_passes,
        "num_skip": num_skipped,
        "num_fail": num_failed,
        "failed_results": failed_tests
      };

      fulfill(metrics);
    });
  });
}

1 个答案:

答案 0 :(得分:1)

变化:

  Promise.all(promises).then(results => {
    failed_tests.push(results)
  }).catch(err => {
    console.log(err)
  });

  var metrics = {
    "total_tests": num_tests,
    "num_pass": num_passes,
    "num_skip": num_skipped,
    "num_fail": num_failed,
    "failed_results": failed_tests
  };

  fulfill(metrics);

为:

  Promise.all(promises).then(results => {
    failed_tests.push(results)
    var metrics = {
      "total_tests": num_tests,
      "num_pass": num_passes,
      "num_skip": num_skipped,
      "num_fail": num_failed,
      "failed_results": failed_tests
    };

    fulfill(metrics);
  }).catch(err => {
    console.log(err)
  });

原因是,在执行fulfill语句中的函数之前,正在创建度量标准并调用.then