访问范围外的变量?的NodeJS

时间:2016-03-06 17:03:37

标签: 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);

运行此命令会给出" undefined"。如何访问函数figlet对函数figlet外部定义的变量结果所做的更改。

2 个答案:

答案 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)

@ answer num8er完全正确。

我个人喜欢使用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);
});