Node JS如何获取外部查询数据 [英] Node JS How to get the query data outside

查看:54
本文介绍了Node JS如何获取外部查询数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node js的新手,只是我最近几天尝试实现此功能,但无法修复

I am new from Node js , just i am trying implementing this functionality last few days but i am unable to fix

exports.get_exercises_for_trainer = function(req, res)
    {

                connection.query('SELECT * FROM ag_exercise', function(err, exercise)
                 {


                    console.log('------------------------------before add fields ----------------------------------');
                    console.log(exercise);

                    for (var i in exercise)
                  {

                        fields(exercise[i].wt_id, function(result1) {


                                    exercise[i].wt_fields = result1; //here i am adding result set of other query but i am not geting this fields data

                                    console.log(result1) //but i printed here working fine but i need this result1 data out side query 

                          });

                    }

                    console.log('------------------------------after add fields ----------------------------------');
                    console.log(exercise);
                    res.render('pages/trainer_home.ejs',{page_title:"Exercise Create",exercise:exercise});

                    });


          }

        function fields(wt_id,callback) 
        {
            connection.query('SELECT *  FROM ag_workout_type_fields  WHERE wt_id = "'+wt_id+'"', function( err1, result1){

                  callback(result1);

             });

             }

我还有一个查询?在节点js中:如果表具有用户,则用户具有不同的关系表,例如订单,配置文件,地址

I have one more query ? in node js : If table having users , users having different relation tables like orders , profiles , address

如何实施

首先我要吸引用户
用户循环
获取每个用户的个人资料,地址,订单
最终用户循环

First i am getting users
User loop
getting every user profiles ,address,orders
end user loop

但在上述情况下,我无法在node js中实现,但在php中却非常简单,例如

but above scenario i am unable to implement in node js but in php very simple like this

$get_users = ... //users data

foreach($getusers as $usr)
{

 $usr->orders = //orders data
.... like etc 
} 

推荐答案

这里有三个主要问题,我将分别解决.

There are three main questions here, I will adress each seperately.

问题1::创建异步函数时,如何在该函数之外访问数据?

Question 1: When making an async function, how do I then access my data outside that function?

来自异步调用的所有数据都可以通过回调,事件侦听器或Promise(精美的回调和事件侦听器处理程序)进行访问.在大多数情况下,您将只使用回调.因此,而不是:

All data from async calls are accessed via callback, event listeners or promises (a fancy callback and event listener handler). For the most part, you are going to just be using callbacks. So, instead of :

get_user = function(user_id){
    //Do some stuff to get the user
    return the_user;
};
var user = get_user('1234');
//do whatever you want with user

您将看到:

get_user = function(user_id,callback){
    //Do some stuff to get the user
    callback(null,the_user);
}
get_user('1234',function(err,user){
    //do whatever you want with user
});

当我们转到问题3时,您将看到您所说的更复杂的用例.

When we get to Question 3, you will see the more complicated use case you were speaking of.

问题2:如何遍历我的数据,对每一行执行后续查询,然后将该数据附加到当前数据中?

Question 2: How do I loop through my data, perform a subsiquent query on each row, and append that data to my current data?

这里有几个问题.

  1. 每次查询数据库时,您都在执行异步功能,因此您需要相应地管理所有这些回调.幸运的是,有一些很棒的工具可以为您做到这一点,我们将使用异步.
  2. 每次在for循环中调用异步函数时,for循环都会继续,因此迭代器将被覆盖,但是异步函数尚未完成,因此您将获得各种意外结果,例如消失的变量,或映射错误的结果.您可以使用JavaScript闭包来处理此问题,也可以再次依赖像async这样的库来为您全部处理.

我们不会将其传递给查询结果,而是将其传递给async.forEachOf,我们将使用它来修改现有数组并将后续查询的结果附加到主查询的行中.重要的是要注意,forEachOf将并行运行后续查询,因此您不应使用单个数据库连接,而应使用池.如果必须使用单个数据库连接,请改为使用forEachOfSeries.

Instead of running a for loop over your queries results, we're going to pass it to async.forEachOf, which we will use to modify the existing array and append the results of the subsequent queries to the primary query's rows. It is important to note that forEachOf will run the subsequent queries in parallel, so you should not be using a single database connection, but a pool. If you MUST use a single database connection, use forEachOfSeries instead.

async = require('async');
exports.get_exercises_for_trainer = function(req, res){
    connection.query('SELECT * FROM ag_exercise', function(err, exercises)
    {
        console.log('------------------------------before add fields ----------------------------------');
        console.log(exercises);
        async.forEachOf(exercises,function(exercise,index,callback){
            connection.query('SELECT * FROM ag_workout_type_fields WHERE wt_id = "' + exercise.wt_id + '"', function( err, result1){
                if(err)return callback(err1);
                exercises[index].wt_fields = result1; //Modify original array
                return callback();
            });
        },function(err){
            if(err){return;} //do some error handling
            console.log('------------------------------after add fields ----------------------------------');
            console.log(exercises);
            res.render('pages/trainer_home.ejs',{page_title:"Exercise Create",exercise:exercises});
        });
    });
};

问题3:如何执行许多相关但不同的查询,以便可以填充有关对象的信息?

Question 3: How do I perform many related but different queries so that I can populate information about my object?

这是异步库的另一个很好的用法.在这种情况下,由于查询都是不同的,因此我们将使用并行而不是forEachOf.

This is another great usage of the async library. In this case since the queries are all different, we'll use parallel instead of forEachOf.

async = require('async');
populate_user = function(user,_callback){
    async.paralell({
        profile: function(callback){
            var sql = "SELECT * FROM profiles WHERE user_id = " + user.id + " LIMIT 1 ";
            var connection.query(sql,function(err,rows,fields){
                if(err)return callback(err);
                if(rows.length === 1)return callback(null,rows[0]);
                return callback(null,[]);
            });
        },
        address: function(callback){
            var sql = "SELECT * FROM addresses WHERE user_id = " + user.id + " LIMIT 1 ";
            var connection.query(sql,function(err,rows,fields){
                if(err)return callback(err);
                if(rows.length === 1)return callback(null,rows[0]);
                return callback(null,[]);
            });
        },
        orders: function(callback){
            var sql = "SELECT * FROM orders WHERE user_id = " + user.id;
            var connection.query(sql,function(err,rows,fields){
                if(err)return callback(err);
                if(rows.length > 0)return callback(null,rows); //notice how this one could have multiple results so we're returning them all
                return callback(null,[]);
            });
        },
    },
    function(err,result){
        if(err)return _callback(err);
        for(var att in result){user[att] = result[att];}
        callback(null,user);
    }
}
user = {id:1234};
populate_user(user,function(err,populated_user)){
    console.log(user); //wow notice how it's populated too!
    console.log(populated_user); //this is really just a new handle for the same object
});

我想指出的是,没有一个经过测试,甚至没有经过语法测试,因此可能需要一些修改.

I want to note that NONE of this was tested, not even for syntax, so it may take a little reworking.

这篇关于Node JS如何获取外部查询数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆