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);
运行此命令会给出" undefined"。如何访问函数figlet对函数figlet外部定义的变量结果所做的更改。
答案 0 :(得分:7)
它的异步代码。它不能回报。必须有回调并在完成工作后做出回应。
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.
});
答案 1 :(得分:4)
我个人喜欢使用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);
});