생성 된 함수를 직렬로 호출하는 데 문제가 있습니다. 비동기 라이브러리를 사용하고 있으며 콜백 호출이 필요없는 경우 코드가 작동하는 것 같습니다. 실제 시나리오를 추가하면 오류가 발생합니다. 여기 비동기 직렬로 생성 된 함수를 호출하는 중
가 작동하는 예입니다 0 ~ 4의 배열을 반환합니다Scrape.prototype.generatePageFunctions = function() {
var functionList = new Array(), self = this;
for (var i = 0; i < this.pageSet; i++) {
(function(i) {
functionList.push(function(cb) {
// Inner functions which will be called in seriers
var timeoutTime = parseInt(Math.random() * 5000 + 3000, 10);
setTimeout(function() {
self.setIndex(i);
self.getSite(function(result) {
// Async callback to pass the data
cb(null, result);
});
}, timeoutTime);
});
})(i);
}
return functionList;
}
오류는 다음과 같습니다
Scrape.prototype.generatePageFunctions = function() {
var functionList = new Array(), self = this;
for (var i = 0; i < this.pageSet; i++) {
(function(i) {
functionList.push(function(cb) {
// Inner functions which will be called in seriers
var timeoutTime = parseInt(Math.random() * 5000 + 3000, 10);
setTimeout(function() {
self.setIndex(i);
//self.getSite(function)
cb(null, i);
}, timeoutTime);
});
})(i);
}
return functionList;
}
Scrape.prototype.run = function() {
var functionList = this.generatePageFunctions();
async.series(functionList, function(err, results) {
console.log('Job is completed ');
console.log(results);
});
}
지금 콜백에 넣어 다음 사이트 및 다운로드와 같은 실제 시나리오를 추가하는 이와 같이 결과 iterator 변수 i 대신에 전달하더라도 :
/home/risto/scrape/node_modules/async/lib/async.js:185
iterator(x.value, function (err, v) {
^
TypeError: Cannot read property 'value' of undefined
at /home/risto/scrape/node_modules/async/lib/async.js:185:23
at /home/risto/scrape/node_modules/async/lib/async.js:108:13
at /home/risto/scrape/node_modules/async/lib/async.js:119:25
at /home/risto/scrape/node_modules/async/lib/async.js:187:17
at /home/risto/scrape/node_modules/async/lib/async.js:491:34
at /home/risto/scrape/scraper/scrape.js:114:13
at /home/risto/scrape/scraper/scrape.js:64:16
at Object.<anonymous> (/home/risto/scrape/scraper/engines/google.js:58:12)
at Function.each (/home/risto/scrape/node_modules/cheerio/lib/api/utils.js:133:19)
at [object Object].each (/home/risto/scrape/node_modules/cheerio/lib/api/traversing.js:69:12)
// 편집
완전한 콜백에 추가 된 결과 만 첫 번째 것이고 다른 함수는 호출되지 않습니다. 또한 정보가 필요하다면 함수는 객체 리터럴을 반환합니다.
더 유용한 답변을 받아 들여야합니다. – rekire
True는 해당 기능을 잊어 버렸습니다. :), fixed –