繁体   English   中英

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

[英]How to get data from callback function to another function in Nodejs + Express

我知道这是一个愚蠢的问题,但我找不到适合我要求的答案。 我正在尝试从返回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);
            }
        });

    }

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

问候

除非您将变量提升到内部函数范围之外,否则不能这样做。 但是您仍然需要处理同步问题。

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

如果这不在forEach内,则显然可以将res.render放入第二个回调中,但是您需要更复杂一些。

我建议使用包async

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM