Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variable outside scope? nodejs

Tags:

node.js

function art(dataToArt){
  var figlet = require('figlet');
var result;
figlet(dataToArt, function(err, data) {
    if (err) {
        console.log('Something went wrong...');
        console.dir(err);
        return;
    }
    var result = data;
});
return result;
}

test = art('Hello World');

console.log(test);

Running this gives "undefined". How to access the changes made by function figlet to the variable result defined outside the function figlet.

like image 450
Garvit Jain Avatar asked Mar 06 '16 17:03

Garvit Jain


1 Answers

It's asynchronous code. It cannot do return. It must have callback and respond after job done.

var figlet = require('figlet');

function art(dataToArt, callback)
{ 
    figlet(dataToArt, function(err, data) { 
        if (err) { 
            console.log('Something went wrong...'); 
            console.dir(err); 
            return callback(''); 
        } 

        callback(data);
    }); 
} 


art('Hello World', function (data){
    console.log(data);
    // also You can do operations here.
    // for example can save to db or send to somewhere.
});
like image 78
num8er Avatar answered Oct 21 '22 11:10

num8er