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

运行此命令将得到“未定义”。如何访问功能figlet对在功能figlet外部定义的变量结果所做的更改。

最佳答案

它是异步代码。它不能返回。它必须具有回调并在完成工作后做出响应。

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

09-25 18:35