如何从回调函数获取数据到Nodejs + Express中的另一个函数

时间:2015-09-21 18:32:11

标签: javascript json node.js

我知道这是一个愚蠢的问题,但我无法找到符合我要求的答案。 我试图从一个返回Json的web服务中获取数据并将其添加到我已经从另一个Web服务请求中使用另一个异步函数内部获得的其他数据的数组中。

以下是代码:

main.js

server.get('/app', function(req, res){

//This code get the categories data from a webservice
data.getdata.categories(userid, function(err, datos){
    datos.forEach(function(dato){

        //This function get data from a diferent webservice that return a Json
        data.getdata.subs(dato.name, function(response){
                if(response){
                    //response.total bring me an integer, this is the variable that i need to pass thru the res.render variables 
                    dataq = response.total; 
                }
                //for each category i need to store the number of subscription (the integer in response.total)
                datos.number = dataq;
            });         

    });

    res.render('app', {
        user : req.session.user,
        usertype: req.session.usertype,
        number : userid,
        listusers: ListUsers,
        listsubs: datos, // Here i get the data without the number value that i tryed to add in 2nd function
        permit: datos.length
    }); 
});

});

在model.js中

//This one request to a first webservice that return a Json
categories: function(user_id, callback){
        request('http://localhost:3030/getdata/*/subscriptions/user_id/'+user_id, function(error, res, body) {
            if (error) { 
                callback("error", null); 
            }else{
                result = JSON.parse(body);
                callback(null, result);
            }

        });
    },

    //This one request to another webservice that return a Json
    subs: function(cat, callback){
        request('http://104.131.7.130:8080/event/'+cat, function(error, res, body){
            if(error){
                return callback("error", null);
            }else{
                result2 = JSON.parse(body);
                return callback(result2);
            }
        });

    }

如何将数据从第二个回调函数传递给第一个回调函数?

问候

1 个答案:

答案 0 :(得分:0)

你不能,除非你在内部函数范围之外提升变量。但是你仍然需要处理同步问题。

请记住,您将在此处运行异步,因此您编写函数的方式,res.render可能会(甚至可能)在data.getdata.subs调用之前运行。

如果这不在forEach内,你显然只是将你的res.render放在第二个回调中,但你需要更复杂的东西。

我会推荐包async

具体来说,请看async.each(arr, iterator, [callback])