0

below is my function:

function searchAccessToken(emailAddress){
    var sql = "SELECT accessToken FROM device WHERE email_address = '" + emailAddress + "'";
    console.log(sql);
    var token = "";
    db(function(err,conn){
        conn.query(sql, function(err,results){
            if(err){
                conn.release();
                throw err;
            }else if(results.length){
                conn.release();
                token = results[0].accessToken;
                return token;
            }else{
                conn.release();
                return token;
            }
        });
    });
}

this is how I called the function:

var userAccessToken = searchAccessToken(name);

But when I tried to debug, userAccessToken returns undefined which by right it should return a string

EDITED: (but still does not work). Added callback but still does not work.

function searchAccessToken(emailAddress){
    var sql = "SELECT accessToken FROM device WHERE email_address = '" + emailAddress + "'";
    console.log(sql);
    var token = "";
    db(function(err,conn,callback){
        conn.query(sql, function(err,results){
            if(err){
                conn.release();
                return callback(err);
            }else if(results.length){
                conn.release();
                token = results[0].accessToken;
                return callback(token);
            }else{
                conn.release();
                return callback(token);
            }
        });
    });
}
jdotdoe
  • 477
  • 2
  • 6
  • 18
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Felix Kling May 11 '18 at 03:33
  • you should use callback, promise or async await for this situation. searchAccessToken() return undefined because it does not wait for the result of conn.query – Hugevn May 11 '18 at 03:37
  • I replaced return token TO return callback(token); but it still returns undefined – jdotdoe May 11 '18 at 03:56
  • You haven't understood the problem yet. `searchAccessToken` is the function that needs to accept and be passed a callback. You cannot just make the function you pass to `db` have a third parameter. – Felix Kling May 11 '18 at 04:09

0 Answers0