如何在节点js中使数组失去功能?

时间:2015-12-02 12:04:19

标签: javascript mysql node.js

我们可以从这个connection.query函数中访问result_cont吗?我想从这个函数中访问这个结果数组。

var results = [];
        for (var i = 0; i < result.length; i++) {


          connection.query( "select c.`uid`, u_p.`first_name`, u_p.`last_name` from `contents` as c inner join `user_profiles` as u_p on u_p.`user_id` = c.`user_id`  where place_id ='"+result[i].id+"' ", handleResults) 

            function handleResults(err_cont, result_cont) {

                results.push(result_cont);
            }
        };

        res.send(results);   // returning empty array []

编辑抱歉,我忘记在代码中添加循环。现在这是实际的代码。

2 个答案:

答案 0 :(得分:0)

使用async queue

var async = require("async");

var q = async.queue(function (result, callback) {
    connection.query( "select c.`uid`, u_p.`first_name`, u_p.`last_name` from `contents` as c inner join `user_profiles` as u_p on u_p.`user_id` = c.`user_id`  where place_id ='"+result.id+"' ", callback);
}, 2 /* here you can choose concurrency of the queries */);

var results = [];
q.drain = function() {
    console.log("All queries executed %d", results.length);

    // Handle all your results with a simple loop
    for (var i = 0; i < results.length; i++) {
      // results[i]
    }
}

// Push all your results to the queue
for (var i = 0; i < result.length; i++) {

    q.push(result[i], function (err_cont, result_cont) {

      /// Handle each result at the time
      console.log(result_cont );
      results.push(result_cont);
    })
 };

答案 1 :(得分:0)

您需要将此回调链接到另一个函数以获取异步返回值,使用promises或像async.js这样的控制流库将一系列函数链接在一起。如果你只是想在函数体内打印值put console.log。