I have a node.js code in which I want to wait for all my sql queries to complete and then process the next part.
Here I am returning the promises and storing in the array. After all the promises are returned I want to do some calculation. But it seems that Promises.all() is not waiting for the promises to get resolve and gives me 0 in the calculation stage ?
Can someone help me with this, where I am doing the mistake ?
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);
});
via Anshul Jindal
No comments:
Post a Comment