0

I'm trying to get the results returned from the database, according to some documents I have to use call back, I'm trying but the result is still undefined, please help me

// app.js file
var db = require('./database');
var access_token;

db.page_access_token(page_id, function(err, content) {
    if (err) {
        console.log(err);
    } else {
        access_token = content;
        console.log(access_token); // response conrrect
    }
});
console.log(access_token); // response undefined

// database.js file
module.exports = {

    page_access_token : function(page, callback){
        conn.query('SELECT access_token FROM facebook_pages WHERE ?', {page : page}, function(err, row) {
            if (err) {
                callback(err, null);
            } else 
                callback(null, row[0].access_token);
        });
    }

}
newsshare24h
  • 69
  • 1
  • 11

1 Answers1

1

A database call is Asynchronous (It takes time to complete the execution). You are assigning value to access_token in the callback and you are logging access_token variable outside of the callback function. Here, access_token is undefined because of console.log() outside of callback is executed before the console.log() in the callback function as it is async operation. If you need to use access_token outside of callback then write a function and pass access_token to the function as a parameter. e.g -

db.page_access_token(page_id, function(err, content) {
    if (err) {
        console.log(err);
    } else {
        access_token = content;
        doSomeWork(access_token);
        console.log("Access token in callback -->>"+ access_token); 
    }
});

function doSomeWork(acc_token){
   console.log("Access token in doSomeWork -->>"+ acc_token);
}

Darshan Devrai
  • 566
  • 5
  • 10