2016-03-07 32 views
0

所以,我們試圖給我們express服務器改寫成Rx。它是目前使用async所有流操作。代碼如下所示:異步轉換到Rx.js

var async = require('async'); 

function getCountAndChannels(name, cb){ 
    var tasks = [ 
     function(cb) { 
      //does a mongoDB search and returns count 
     }, 
     function(cb) { 
      //does a findOne mongoDB search and returns 
     } 
    ]; 
    async.parallel(tasks, cb); 
} 

router.get('data', function(req, res) { //router is the express router 
    var recorders = req.query.recorders.split(','); 

    async.map(recorders, function(name, cb) { 
     getCountAndChannels(name, cb); 
    }, function(err, countsAndChannels) { 
     if(err) throw err; 

     // here countsAndChannels is an array with first element the count 
     // and second element the document. 

     // do other async stuff based on the results 

     res.status(200).json('send some calculations'); 
}); 

這裏我必須做的事情是循環遍歷的recorders數組,併爲每一個計算兩個MongoDB的搜索。我曾嘗試使用Rx.Observable.merge,它不返回數組中的結果,而是在回調的兩個不同調用中返回結果。所以,後來我試着Rx.Observable.zip我相信這是我要找的。

問題是我不知道如何遍歷recorders並在所有操作完成時發送結果。因爲一個簡單的forEach循環將拋出一個Cannot set headers after they are sent錯誤。

這是我到目前爲止有:

recorders.forEach(recorder => {   
    Rx.Observable.zip([ 
     search1, 
     search2 
    ]).subscribe(
     (countsAndChannels) => {     
      // do stuff 
      res.send('the results'); 
     }, 
     err => res.status(500).json(err), 
     () => res.send('OK') 
    ); 
}); 

以前沒有使用過的Rx,所以任何幫助表示讚賞。

+1

來自Rx中async.js的運營商替代方案的巨大列表http://xgrommx.github.io/rx-book/content/mappingr_rxjs_from_different_libraries/async/index.html – xgrommx

+0

@xgrommx謝謝!我在搜索前沒有找到這篇文章。會看看 – XeniaSis

+0

再次感謝@xgrommx!它幫助我解決了這個問題:) – XeniaSis

回答

0

這可能是更容易的刻錄機的列表轉換爲可觀察到的數據流,然後flatMap在每個記錄(即執行你的異步處理),然後調用toArray到所有的結果存儲到一個數組:

var recorder$ = Rx.Observable.from(recorders); 
var countsAndChannels$ = recorder$ 
    .flatMap(performAsyncTask); 

// allResults$ will emit once all of the async work is complete 
var allResults$= countsAndChannels$.toArray(); 

allResults$.subscribe(results => { 
    // Send response to client; 
}); 
+0

謝謝,已經解決了它,但我也會嘗試你的解決方案。 – XeniaSis