Javascript:当未定义值时,方法返回undefined

时间:2013-07-10 20:19:33

标签: javascript node.js

我做

if (program.url) {
        checkJson = checkUrl(program.url, program.checks);
        console.log('checkJson:', checkJson);
    }

var checkUrl = function (url, checksfile) {
    var checks = loadChecks(checksfile).sort();
    rest.get(program.url).on('complete', function(data) {
        var out = {};
        $ = cheerioUrlData(data);
        for (var ii in checks) {
            var present = $(checks[ii]).length > 0;
            out[checks[ii]] = present;
        }
        console.log(out); // <<-- This console
        return out;
    });
};

控制台看起来像

{ '.about': true,
  '.blank': true,
  '.faq': true,
  '.footer': true,
  '.heading': true,
  '.logo': true,
  '.navigation': true,
  '.order': true,
  '.pitch': true,
  '.section1': true,
  '.section2': true,
  '.social': true,
  '.subheading': true,
  '.thermometer': true,
  '.video': true,
  h1: true }

console.log('checkJson:', checkJson);打印

checkJson: undefined

这里有什么不对?

1 个答案:

答案 0 :(得分:1)

return out;从“完整”回调中返回,而不是从checkUrl返回。 checkUrl立即返回(在rest.get返回之前)。您需要使用回调来获取您要查找的值:

if (program.url) {
       checkUrl(program.url, program.checks, function(result) {
            console.log(result);
       } );
}

var checkUrl = function (url, checksfile, callback) {
    var checks = loadChecks(checksfile).sort();
    rest.get(program.url).on('complete', function(data) {
        var out = {};
        $ = cheerioUrlData(data);
        for (var ii in checks) {
            var present = $(checks[ii]).length > 0;
            out[checks[ii]] = present;
        }
        console.log(out); // <<-- This console
        callback(out);
    });
};