Node.js 未在Node promise.each中处理数组最后一个元素的结果

Node.js 未在Node promise.each中处理数组最后一个元素的结果,node.js,promise,bluebird,Node.js,Promise,Bluebird,我有一个代码段来运行mysql主机数组中的元素列表,任务是迭代数组中的每个元素-使用elementhostname连接到mysql,对其运行查询,并将结果生成json 最后一个元素的结果不会在最终数组中捕获,而其他元素则会捕获 下面是配置数组和代码段 配置: config.mysql.list = ['host1', 'host2', 'host3' , 'host1']; 主机名可以重复。响应中结果对象的计数应等于数组中的元素数 const config = require('../../

我有一个代码段来运行mysql主机数组中的元素列表,任务是迭代数组中的每个元素-使用elementhostname连接到mysql,对其运行查询,并将结果生成json

最后一个元素的结果不会在最终数组中捕获,而其他元素则会捕获

下面是配置数组和代码段

配置:

config.mysql.list = ['host1', 'host2', 'host3' , 'host1'];
主机名可以重复。响应中结果对象的计数应等于数组中的元素数

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;

我对代码片段中真正缺少的内容感到有点困惑。

将return放在conn.querysyncgry前面。您需要返回从conn.queryAsync返回的承诺。希望这有帮助。

将return放在conn.queryAsyncqry前面可以解决问题吗?在您的示例中,host1有两次。这只是你的代码片段中的错误吗?@PierreMallet这只是一个例子。。可以是任何主机。但是,不考虑最后一台主机的结果。此外,没有错误,只是最后一次迭代的结果没有被捕获到最终输出中。我认为Skyler注释是关键:您不在conn.queryAsync之前返回,因此承诺返回未定义,并立即解析,因此承诺在最后一次getConnection之后解析,而不是在最后一次queryAsync之后解析。然后,当您执行res时,最后一个结果还没有进入ARR状态。json@Skyler我会检查一下,然后告诉你