2016-10-04 27 views
0

更新:澄清和修改代碼,以反映我真的想要的東西,也就是發送流媒體響應,也就是發回匹配的結果,因爲它們到達從他們自己的async匹配過程中。發送與異步操作流響應REST查詢

考慮(使用expressjs -ish代碼)

app.post('/', jsonParser, function (req, res) { 
    if (!req.body) return res.sendStatus(400) 

    // matches is not needed for this scenario so 
    // commenting it out 
    // var matches = []; 
    req.body.forEach(function(element, index) { 

     foo.match(
      element, 
      function callback(error, result) { 
       if (error) { 
        console.log(error); // on error 
       } 
       else { 
        ⇒ if (some condition) { 
         // matches.push(result); 
         ⇒ res.send(result); 
        } 
       } 
      } 
     ); 
    }); 

    // moved this above, inside the callback 
    // ⇒ res.send(matches); 

}); 

輸入到post('/')是術語的陣列。每個術語使用foo進行匹配,每次調用後都有callback。我想發回所有符合「某些條件」的比賽(參見上述代碼中的)。理想情況下,最好發送流式響應,即在匹配發生時發回響應(因爲foo.match()可能需要一段時間)。我如何去做這件事?

+0

你的問題是關於流或如何創建一個數組,最終會發回給客戶端? –

+0

已更新的問題,以澄清我想發回流回應,而不是最終陣列。感謝您注意到混淆。 – punkish

回答

1

有沒有像這樣的東西適合你?我使用了stream-array模塊。可能這對你有幫助? How to emit/pipe array values as a readable stream in node.js?

var streamify = require('stream-array'); 

app.post('/', jsonParser, function (req, res) { 
    if (!req.body) { 
    return res.sendStatus(400); 
    } 

    var matches = []; 
    req.body.forEach(function (element, index) { 
    foo.match(
     element, 
     function callback(error, result) { 
     if (error) { 
      console.log(error); // on error 
     } else { 
      if (some condition) { 
      streamify([result]).pipe(res); 
      } 
     } 
     } 
    ); 
    }); 

    // res.json(req.body); 
}); 
+0

不幸的是它不起作用,儘管它可能在我的一端是錯的。讓我再解釋一遍。我不想等待構建整個結果數組。我想發回從'foo'到達的結果,這是一個異步操作。無需在兩者之間存儲結果,只需在它們到達時發送它們即可。我投了你的答案,因爲它可能是我沒有正確實施它,但它看起來很有希望。 – punkish