2013-04-12 78 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

我完全錯過了響應回調的範圍。請求模塊看起來非常有用,我會研究它,謝謝! –

相關問題