Promises.all()不等待承诺的解决

时间:2017-06-10 09:41:14

标签: javascript node.js

我有一个node.js代码,我想等待所有的SQL查询完成 然后处理下一部分。

这里我将返回promises并存储在数组中。 在返回所有承诺之后,我想做一些计算。 但似乎Promises.all()不等待承诺得到解决并在计算阶段给我0?

有人可以帮我解决这个问题吗?

var results= [];
    var salaries = 0;
    var numberOfWorking = 0;
    var numberOfNotFound = 0;
    var numberOfFound = 0;
    var averageSalary = 0;
    var promises = [];
    for (grad in graduates) {
      promises.push(function () {
        return new Promise(function (resolve, reject) {
          var entree = graduates[grad];
          console.log("entree:", JSON.stringify(entree));
          var query = "SELECT Salary FROM employment WHERE FirstName='" + entree['firstName'] + "' AND MiddleName='" + entree['middleName'] + "'" +
            "AND LastName='" + entree['lastName'] + "' AND DOB='" + entree['birth'] + "'";

          connection.query(query, function (err, rows, fields) {
            if (!err) {

              if (rows.length == 0) {
                numberOfNotFound = numberOfNotFound + 1;
              }
              else {

                var Salary = parseInt(rows[0].Salary, 10)
                console.log("Salary", Salary);
                numberOfFound = numberOfFound + 1;
                salaries += Salary;
                if (Salary > 0) {
                  numberOfWorking = numberOfWorking + 1;
                }
                console.log("salaries", salaries);
                console.log("numberOfFound", numberOfFound);
                console.log("numberOfWorking", numberOfWorking);
                resolve(true);
              }
            }
            else {
              console.log(req.body);
              console.log("ERROR:", err);
              reject(err);
            }
          });
        });
      });
    }
    Promise.all(promises).then(function (dataArr) {
      if (numberOfFound > 0) {
        averageSalary = salaries / numberOfFound;
      }
      else {
        averageSalary = 0;
      }
      console.log("salaries", salaries);
      console.log("averageSalary", averageSalary);
      console.log("numberOfFound", numberOfFound);
      console.log("numberOfWorking", numberOfWorking);
      var tosendOnePkg = {};

      tosendOnePkg = {
        "packageID": pId,
        "numberOfPersons": numberOfFound + numberOfNotFound,
        "numberOfWorkingPersons": numberOfWorking,
        "notFoundPersons": numberOfNotFound,
        "averageSalary": averageSalary
      }
      tosendOnePkg['packageID'] = package;
      results.push(tosendOnePkg);
    });

1 个答案:

答案 0 :(得分:0)

问题是您要向promise数组添加函数,请参阅示例的第9行:

promises.push(function () {
    return new Promise(function (resolve, reject) {
        ...
    }
});

相反,您应该添加承诺本身:

promises.push(new Promise(function (resolve, reject) {
    ...
});