7
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.

Garvit Jain
  • 1,862
  • 2
  • 19
  • 27
  • 1
    It seems like `figlet` is an asynchronous function. You can't. You need to do all your work inside the callback. – Explosion Pills Mar 06 '16 at 17:07
  • I'm using https://www.npmjs.com/package/figlet and I've never ever used nodejs – Garvit Jain Mar 06 '16 at 17:08
  • "[Why is my variable unaltered after I modify it inside of a function?](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron)" Though, you are declaring `result` in multiple scopes, so you're returning a different `result` than you're assigning `data` to. However, changing that (`result = data;` without `var`) won't fix the issue of execution timing. – Jonathan Lonowski Mar 06 '16 at 17:08
  • ... and you never ever used JavaScript in the first place? – crackmigg Mar 06 '16 at 17:08
  • Just look at the "simple example" in the figlet doc where to use the result `data` of your asynchronous callback function. – crackmigg Mar 06 '16 at 17:11

2 Answers2

9

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.
});
num8er
  • 18,604
  • 3
  • 43
  • 57
5

The answer by @num8er is perfectly correct.

I personally like using promises:

var figlet = require('figlet');

function art(dataToArt) {
    return new Promise(function(fullfil, reject) {
        figlet(dataToArt, function(err, data) {
            if (err) {
                reject(err);
            } else {
                fullfil(data);
            }
        });
    });
}

art('Hello World').then(function(result) {
    console.log(result);
});
Community
  • 1
  • 1
Perspectivus
  • 972
  • 1
  • 9
  • 22
  • 1
    This worked locally but not in my [Telegram Bot](https://telegram.me/bigletterbot) Anyways thanks for the Answer, sorry I cannot +1 your answer because stackoverflow isn't letting me. – Garvit Jain Mar 07 '16 at 03:38