2013-04-12 30 views
0

我让我的Request对象排队了单个HTTP请求,并使用process.nextTick逐个处理它们。但是,我收到一个错误,我不知道如何解决:尝试排队http请求时发生process.tick错误

node.js:244 
     callback(); 
     ^
TypeError: undefined is not a function 
    at process.startup.processNextTick.process._tickCallback (node.js:244:9) 

我不知道我在做什么错。这是相关的课程。

var Request = function() { 
    return this; 
}; 

Request.prototype = { 
    queue_: [] 
}; 

Request.prototype.send = function(url, done) { 
    this.queue_.push(new QueueableRequest(url, done)); 
    this.processRequest_(); 
} 

Request.prototype.processRequest_ = function() { 
    if (this.queue_.length > 0) { 
     var request = this.queue_.shift(); 
     var data = ''; 
     http.get(request.url_, function(res) { 
      res.setEncoding('utf8'); 
      res.on('data', function(chunk) { 
       data += chunk; 
      }).on('end', function() { 
       request.callback_(null, JSON.parse(data)); 
       process.nextTick(this.processRequest_); 
      }).on('error', function(err) { 
       request.callback_(err, null); 
       process.nextTick(this.processRequest_); 
      }); 
     }); 
    } 
} 

我的另一个问题是,这是否是一个很好的方法来减缓我的HTTP请求?我正在尝试做的是...我为线程列表(大约15-20)发出HTTP请求,然后为每个线程发出另一个请求以获取其答复。有时在回复中,我必须再次请求深度嵌套的回复。我最初的解决方案是简单地为每个请求调用http.get,但是我发现我的node.js在几个请求后停止响应,我必须不断重新启动服务器并刷新页面。我的想法是,我可能一次发送太多的请求,所以我试图实现这个队列。

回答

2

您的活动处理程序中的this不正确,因此您的this.processRequest_undefined

Request.prototype.processRequest_ = function() { 
    // Assign the outer request object to a variable so you can access it. 
    var self = this; 

    if (this.queue_.length > 0) { 
     var request = this.queue_.shift(); 
     var data = ''; 
     http.get(request.url_, function(res) { 
      res.setEncoding('utf8'); 
      res.on('data', function(chunk) { 
       data += chunk; 
      }).on('end', function() { 
       request.callback_(null, JSON.parse(data)); 
       process.nextTick(function(){ 
        // Call 'processRequest_' on the correct object. 
        self.processRequest_() 
       }); 
      }).on('error', function(err) { 
       request.callback_(err, null); 
       process.nextTick(function(){ 
        // Call 'processRequest_' on the correct object. 
        self.processRequest_() 
       }); 
      }); 
     }); 
    } 
} 

也就是说,你可能会考虑使用request module来简化这一点。

var request = require('request'); 

Request.prototype.processRequest_ = function() { 
    var self = this; 
    if (this.queue_.length > 0) { 
     var requestData = this.queue_.shift(); 
     request(requestData.url_, function(error, response, body){ 
      requestData.callback_(err, err ? null : JSON.parse(body)); 
      process.nextTick(function(){ 
       self.processRequest_(); 
      }); 
     }); 
    } 
}; 
+0

我完全错过了响应回调的范围。请求模块看起来非常有用,我会研究它,谢谢! –

相关问题