CounterFlame CounterFlame - 3 months ago 13
Node.js Question

NodeJS Promises - "Then" not called

I'm new to NodeJS and after spending a few hours trying to understand how Promises work exactly, what seems to be an easy thing still doesn't work.

I'm trying to make a few calls to a database, and once all of those calls are done, do something else. What I have now is the following code, but none of the then-functions are called.

var queries = ['SELECT value FROM tag', 'SELECT url FROM download_link'];
console.log("Starting promises");
var allPromise = Promise.all([queryDatabaseAddToResult(connection, queries[0], result), queryDatabaseAddToResult(connection, queries[1], result)]);
allPromise.then(
function(result) {
console.log("1"); // Does not show up
}, function(err) {
console.log("2"); // Does not show up either
}
);

function queryDatabaseAddToResult(connection, query, result) {
return new Promise(function(resolve, reject) {
connection.query(query, function(err, rows, fields) {
if (err) {
console.log(err);
Promise.reject(err);
}
console.log(rows);
result.tags = JSON.stringify(rows);
Promise.resolve(result);
});
})


}

The calls to the database do get made, as logging the rows show up in the log.

Answer

The problem is that you are not calling the correct resolve and reject functions. It should be:

function queryDatabaseAddToResult(connection, query, result) {
  return new Promise(function(resolve, reject) {
    connection.query(query, function(err, rows, fields) {
      if (err) {
        console.log(err);
        reject(err);
      } else {
        console.log(rows);
        result.tags = JSON.stringify(rows);
        resolve(result);
      }
   });  
})

Note that the resolve and reject calls should not be scoped with Promise.. And you should have used an else to avoid calling resolve once you've called reject.