0

我愿意

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

这里有什么不正确的?

4

1 回答 1

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);
    });
};
于 2013-07-10T20:27:39.717 回答