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.

5
  • 1
    It seems like figlet is an asynchronous function. You can't. You need to do all your work inside the callback. Commented Mar 6, 2016 at 17:07
  • I'm using npmjs.com/package/figlet and I've never ever used nodejs Commented Mar 6, 2016 at 17:08
  • "Why is my variable unaltered after I modify it inside of a function?" 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. Commented Mar 6, 2016 at 17:08
  • ... and you never ever used JavaScript in the first place? Commented Mar 6, 2016 at 17:08
  • Just look at the "simple example" in the figlet doc where to use the result data of your asynchronous callback function. Commented Mar 6, 2016 at 17:11

2 Answers 2

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

Comments

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

1 Comment

This worked locally but not in my Telegram Bot Anyways thanks for the Answer, sorry I cannot +1 your answer because stackoverflow isn't letting me.

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.