2017-10-18 116 views
0

我有一個MEAN應用程序,可以很好地處理單個請求,比如說打電話給/api/products?pid=500。但我最近發現,在「爆發」的請求(我正在更新大約50個產品= 50個請求/api/products?pid=500 *** 550與發佈數據),req.body有時得到一個新的即將到來的請求值。MEAN節點JS請求很多請求的性交

前的應用程序,使通話在選擇產品的一個foreach:

ds.forEach((d, key) => { 
     this.ApiCall.setData('products', { action: 'send-product', data: d }) 
      .subscribe((result) => { 
       //we have results 
      }); 
     }); 
    //setData makes a http.post().map 

回到應用程序/平均分析後,試着合成代碼:

router.route('/') 
.post(function (req, response) { 
    if(req.body.data){ 
     var obj = { id: req.body.data.product_id } 
     if(req.body.data.linked_products){ 
      req.body.data.linked_products.forEach(function(entry) { 
       obj.linked = entry; //more ifs 
      }); 
     } 
     var async = require('async'); 
     async.series({ 
      q2: function(cb){ 
       queryProducts.findOne({id: req.body.data.product_id, null).exec(cb); 
      }, 
      q3: function(cb){ 
       queryCategories.findOne({id: req.body.data.category_id, null).exec(cb); 
      } 
      }, function(err, qResults){ 

      var alreadysent = false; 
      if (qResults.q3) qResults.q3.logs.forEach(function(entry) { 
       if(entry.sent){ 
        alreadysent = true; 
       } 
      }); 
      //more ifs 
      qResults.q3.external_codes.forEach(function(entry) { 
       obj.external_code = entry;//more ifs 
      }); 
      if(req.body.data.price < 0){ 
       response.json({message: "Negative price didn't sent"}); 
       return; 
      } 
      if(qResults.q2.status=="inactive"){ 
       response.json({message: "Inactive didn't sent"}); 
       return; 
      } 
      req.body.data.campaigns(function(entry) { 
       obj.price_offers = entry;//more ifs 
      }); 
      //more ifs and foreach similar 
      queryProducts.update({id: req.body.data.id}, {$push: { synced_products: obj }}, function (err, result) { 
       //HERE I found req.body.data with values of a future request 

       if(!err) 
        response.json({message: "Sent"}); 
       return; 
      }); 
     }); 
    } 
}); 
module.exports = router; 

我明白,發出請求

/api/products?pid=500 
/api/products?pid=501 
/api/products?pid=502 
/api/products?pid=503 
... 

有不同的定時,但是如何可能的是,請求(PID = 501),調用最後一個req.body以獲得req.body的新req(pid = 503)的值? 任何想法如何避免?在帖子後發送異步信息或製作一個

var reqbody = req.body 

謝謝!

+2

請用顯示問題的[mcve]更新您的問題。引用的代碼(如果我們假設在「post」調用中丟失了close paren和semi),應該不會有任何跨請求數據泄露的問題,所以其他地方正在發生某些事情。 –

+0

@ T.J。抱歉抱歉,更新了代碼,謝謝! – Mihai

+0

嘗試使用'let'而不是'var'。 – Sagar

回答

1

我相信這是由於async模塊初始化。從node docs引用:

緩存

模塊是他們第一次加載後緩存。這意味着(除其他外)每次調用require('foo')將得到完全相同的對象返回,如果它將解析爲相同的文件。

多次調用require('foo')可能不會導致模塊代碼被多次執行。這是一個重要的功能。通過它,可以返回「部分完成」的對象,從而允許傳遞依賴被加載,即使它們會導致循環。

要讓模塊多次執行代碼,請導出函數並調用該函數。

當一連串的請求導致重疊執行時,您將有兩個(或更多)使用async變量被「併發」修改。我建議使用某種互斥來控制對變量async的訪問。