【发布时间】:2014-12-25 10:19:15
【问题描述】:
我正在编写一个 Node.js 应用程序,但我无法将我的网络抓取的值返回到我的主 app.get 函数。页面被刮得很好,结果在我的回调中一直到 RETURN,但它实际上并没有返回值。任何帮助将不胜感激!
编辑:这需要是一个纯 javascript 解决方案,并且不使用 jQuery。
在我的 server.js 文件中,我有以下代码:
var machineDetails = helpers.scrapePage();
app.get('/', function (req, res) {
res.render('index', { machineDetails: machineDetails, title: 'VIP IT Dashboard'});
});
在 helpers.js 文件中,我有以下功能
//Requires
httpntlm = require('httpntlm'),
cheerio = require('cheerio');
var userData;
function callSite(callback) {
//Scrape site and get information
var scrape;
httpntlm.get({
url: "http://URLthatIamScraping.com",
username: 'username1',
password: 'password1',
domain: 'companyDomain'
}, function (err, res) {
if (err) return err;
//Sort information for the computer
var $ = cheerio.load(res.body);
var scrape = $('#assetcontent').html();
//Return the html content of the page
callback(scrape);
});
}
exports.scrapePage = function(){
return callSite(function(data) {
//This is called after HTTP request finishes
userData = data;
//ISSUE: userData is not actually making it back to my server.js variable called "machineDetails"
return userData;
});
}
【问题讨论】:
标签: javascript node.js asynchronous callback return