我做
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
这里有什么不对?
答案 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);
});
};