0

i am taking my first steps with node.js and i came across this issue with passing variable in asynchronous way. I have this piece of code im using to create Facebook user:

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

i tried to figure out why the second log isn't working and i ended up reading about synchronous and asynchronous functions, so in attempt to implement what i read i tried coming up with a solution using callbacks, but no success. my last attempt was this:

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);

but its not working... what i am actually trying to achieve its to render this object with my express router var which looks like this:

   router.get('/welcome', securePages, function(req, res, next){
        res.render('welcome', {title:'Welcome to aDating', user:req.tmpPassport});
    })

but i cant figure out how to pass this object only after created...any help please?

2 Answers 2

3

A method of chaining function calls when certain async tasks are done is one way to deal with this.

Looking at the first snippet of code, it would be rewritten as follows:

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Node.js is an asynchronous programming language, a fundamental concept in its core. You either need to use function callbacks (not a good practice) or available npms utilities for async flow.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.