Search code examples
node.jspromisebluebird

Result for last element of the array not processed in Node promise.each


I have a code piece to run through a list of elements in an array (mysql hosts to be precise) and the task is to iterate through each element in the array - connect to mysql using the element(hostname), run a query against it and have the results in a json.

The result for the last element is not captured in the final array, while the others are.

Below are the config array and snippet

Config :

config.mysql.list = ['host1', 'host2', 'host3' , 'host1'];

The hostname can be repeated. The count of result objects in the response should be equivalent to the number of elements in the array.

const config  = require('../../config.js');

//For RESTful API
const express = require('express');
const router = express.Router();
const promise=require('bluebird');
//For MySQL connection
const mysql   = require('mysql');

promise.promisifyAll(config);
promise.promisifyAll(require('mysql/lib/Connection').prototype);
promise.promisifyAll(require('mysql/lib/Pool').prototype);

//Home page venue type wise breakup
router.get('/databaseRecords',function(req,res){
  // Some vars
 let arrStatus =[];
 // Build the connection
 function getConnection(serverHost){
  // Setup the MySQL connection
  let connection = mysql.createConnection({
    host     : serverHost,
    user     : config.mysql.user,
    password : config.mysql.password,
    database : config.mysql.database
  });
  // <- note the second return
  return connection.connectAsync().return(connection);
}
    promise.each(config.mysql.list,function(serverHost) {
      //Create connection
      return getConnection(serverHost).then(function(conn){
        // Slave status
        let qry = 'SELECT * FROM tableName limit 1';
          // Response ?
          conn.queryAsync(qry).then(function(rows){
            let strresponse = JSON.stringify(rows);
            let jsonresponse = JSON.parse(strresponse);
            jsonresponse[0].whichRec=serverHost;
            arrStatus.push(jsonresponse[0]);
            //done
            conn.endAsync();
      });
    });
  }).then(function(){
    // Emit the response
    res.json({'data':arrStatus});
  }).catch(function(err){
    let respErr  = JSON.parse(err.error);
    res.json({'Error':respErr});
  });
});
//Export routes
module.exports = router;

A bit confused as to what I am really missing in the code snippet.


Solution

  • Put return in front of conn.queryAsync(qry). You need to return the promise returned from conn.queryAsync. Hope this helps.