3

In the following code, I am trying to put the results from the first and second query inside a global variable called result. The problem is Promise.all() is not waiting the queries finish and before proceding to then().

How can I solve it?

Code:

var result = {};
Promise.all([
  connection.query('SELECT * FROM analysis', 
    function(err, rows, fields) {
      if (err) throw err;
      result.analysis = rows;
      console.log("query 1");
  }), 
  connection.query('SELECT * FROM analysis_description', 
    function(err, rows, fields) {
      if (err) throw err;
      result.analysis_description = rows;
      console.log("query 2");
  })
])
.then(function(result){
  console.log(result);
  console.log("result");
});

Output:

result
query 1
query 2
mido
  • 24,198
  • 15
  • 92
  • 117
shadow00
  • 245
  • 3
  • 14

2 Answers2

4

like said in the comments, you need to promisify the async calls, either manually:

queryAsync = query => new Promise((resolve, reject) => {
  connection.query(query, (err, rows) => {
    if(err) return reject(err)
    resolve(rows)
  })
})

or preferred way is using library like bluebird:

connection  = require('bluebird').promisifyAll(connection)

and your code can be modified into:

var result = {};
Promise.all([
  connection.queryAsync('SELECT * FROM analysis').then(rows => result.analysis = rows), 
  connection.queryAsync('SELECT * FROM analysis_description').then(rows => result.analysis_description = rows)
]).then(function(result){
  console.log(result);
  console.log("result");
}).catch(e => console.error(e));
mido
  • 24,198
  • 15
  • 92
  • 117
0

Thanks, everyone! Like everyone said, the problem were in the wrong parameter in Promise.all(). This is the code after the changes.

Code:

Promise.promisifyAll(require("mysql/lib/Connection").prototype)

var result = {};
Promise.all([
  connection.queryAsync('SELECT * FROM analysis')
  .then(function(rows){
    console.log(rows);
    result.analysis = rows;
  }), 
  connection.queryAsync('SELECT * FROM analysis_description')
  .then(function(rows){
    result.analysis_description = rows;
  })
])
.then(function(){
  console.log(result);
  console.log("result");
});
shadow00
  • 245
  • 3
  • 14