将变量从回调传递到快速路由器

时间:2015-07-18 09:21:53

标签: javascript node.js asynchronous express

我刚刚开始深入了解node.js,我有这个问题我无法弄明白。

我有我在文件passportAuth.js中创建的用户和回调以确保用户创建。

它看起来像这样:

req.tmpPassport = {};
var fb = new fbgraph.Facebook(accessToken, 'v2.2');
fb.me(function(err, me) {
    req.tmpPassport.me = me;
    fb.my.events(function(err, events) {
        req.tmpPassport.events = events;
        fb.my.friends(function(err, result){
            req.tmpPassport.results = result;
            post_user();
        });
    });
});

//the callback
function post_user() {
    // this function is only executed after the callback from the async call
    return req.tmpPassport;
}

现在,我想将var post_user()返回到我的快速路由器,该路由器位于不同的文件routes.js中并像这样呈现:

router.get('/profile', securePages, function(req, res, next){
    res.render('profile', {title:'Welcome to aDating - Profile', user:--Pass Var Here--});
})

但是我无法弄明白......我试图要求这样的模块:

var fb_user = require('../auth/passportAuth.js');

然后像这样使用它:

   router.get('/profile', securePages, function(req, res, next){
        console.log(fb_user);
        res.render('profile', {title:'Welcome to aDating - Profile', user:req.fb_user});
    })

但它没有用......请有人帮忙吗?

1 个答案:

答案 0 :(得分:-1)

在您的自定义模块" passportAuth"你可以返回一个javascript Promise然后在你的路由器上使用,因为require是一个同步操作,但是你的模块是异步的,所以,如果你返回一个promise,你的路由器会有这个外观:

// fbUser是一个javascript Promise对象

QListWidget list;
list.addItem(index.data().toString());
list.addItems({"1", "2", "3", "4"});
return list.size();

你的模块fbUser是这样的:

var fbUser = require('../auth/passportAuth.js');
router.get('/profile', securePages, function(req, res, next){
    fbUser.then(function(data) {
        res.render('profile', {title:'Welcome to aDating - Profile', user:data.me});
     }).catch(function(err) {
         res.status(500).send(err);
     });
});