Sihoon Kim
Sihoon Kim

Reputation: 1799

Handle queries in a loop in a function

My questions is an extension of the following post: Handle queries inside loop in node.js

var output;
for (var j = 0; j < someArr.length; j++) {
  tVal = someArr[i]; //some manipulation of someArr[i]
  (function(val) {
    connection.query("select id from someTable where someCol = ?", val, function(err, rows, fields) {
      if (err) {
        console.log(err);
      } else {
        output.push(rows[0].someVal); //push query output to this variable
      }
    });
  })(tVal);
}

Now I want to put the whole code into a function and return output. But when I tried it returned an empty set.

Upvotes: 1

Views: 69

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370989

You should turn each query into a Promise, and then return the Promise.all on the array of Promises. No need for that ugly for loop closure, just use .map instead:

function getAllQueries(someArr) {
  const allPromises = someArr.map(val => new Promise((resolve, reject) => {
    connection.query( "select id from someTable where someCol = ?",val, function(err, rows, fields) {
      if (err) return reject(err);
      else resolve(rows[0].someVal);
    });
  }));
  return Promise.all(allPromises);
}

Consume it with .then:

getAllQueries(['foo', 'bar'])
  .then((responses) => {
    console.log(responses);
  });

Upvotes: 1

Related Questions