我正在编写下面的代码,一次解析一个站点API,而不是告诉事件队列它已准备好接下来要解析的对象。我遇到了问题,因为我仍然对JavaScript范围很陌生,并希望从SiteParser发出或调用emitForNext函数。我似乎无法将emitForNext带入错误回调的范围。如何从Node.js中的嵌套函数内发出eventListener(javascript范围问题)
function SiteParser(){
this.emitForNext = function (message) {
this.emit("next", message);
};
this.pullJSON = function (path, processJSON) { //processJSON is a callback function
var options = {
host: 'www.site.com',
port: 80,
path: path
}
//console.log("... processing "+path);
//pulls the entire json request via chunks
http.get(options, function (res) {
var resJSON = ''; //stores the comment JSON stream given in the res
res.on('data', function (chunk) {
resJSON+=chunk;
});
res.on('end', function() {
var obJSON = (JSON.parse(resJSON));
if (obJSON.hasOwnProperty("error")){
console.log(obJSON);
console.log('... ', path, ' does not exist');
//
//NEED A NEXT EVENT EMMITER HERE NEED TO FIGURE OUT SCOPE
//
//
} else {
processJSON(obJSON); //call the callback function
}
}) ;
}).on('error', function (e) {
emitForNext("got error: " + e.message);
});
};
}
我选择了做这种方式,它结束了伟大的工作,对不起,它花了一些时间来实现您的解决方案,我正忙着落实新功能! – Hortinstein 2012-04-04 13:05:25