[英]node.js asynchronous passing variable between functions
我正在使用node.js迈出第一步,并且遇到了以异步方式传递变量的问题。 我使用这段代码来创建Facebook用户:
req.tmpPassport = {};
var fb = new fbgraph.Facebook(accessToken, 'v2.2');
function initUser() {
fb.me(function (err, me) {
req.tmpPassport.me = me;
console.log(req.tmpPassport.me) // works
});
}
console.log(req.tmpPassport.me) // not working -> undefined var
我试图弄清为什么第二个日志不起作用,并且最终阅读了有关同步和异步功能的信息,因此,为了实现所阅读的内容,我尝试提出使用回调的解决方案,但没有成功。 我最后的尝试是:
req.tmpPassport = {};
var fb = new fbgraph.Facebook(accessToken, 'v2.2');
function initUser() {
fb.me(function (err, me) {
req.tmpPassport.me = me;
});
fb.my.events(function (err, events) {
//console.log(events);
req.tmpPassport.events = events;
});
fb.my.friends(function (err, result) {
req.tmpPassport.results = result;
});
}
function passUser(){
console.log(req.tmpPassport);
return req.tmpPassport;
}
cp.exec(initUser, passUser);
但它不起作用...我实际上试图实现的目的是使用我的快速路由器var渲染此对象,如下所示:
router.get('/welcome', securePages, function(req, res, next){
res.render('welcome', {title:'Welcome to aDating', user:req.tmpPassport});
})
但是我无法弄清楚仅在创建后如何传递此对象...任何帮助吗?
一种完成某些异步任务时链接函数调用的方法是一种解决方法。
查看第一段代码,将其重写如下:
req.tmpPassport = {};
var fb = new fbgraph.Facebook(accessToken, 'v2.2');
function initUser() {
fb.me(function (err, me) {
console.log(req.tmpPassport.me) // works
req.tmpPassport.me = me;
// triggers execution of the next step
post_populating_passport();
});
}
function post_populating_passport() {
// this function is only executed after the callback from the async call
console.log(req.tmpPassport.me);
}
Node.js是一种异步编程语言,它是其核心概念。 您要么需要使用函数回调(不是一个好习惯),要么可以使用npms实用程序进行异步处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.