所以,我們試圖給我們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,所以任何幫助表示讚賞。
來自Rx中async.js的運營商替代方案的巨大列表http://xgrommx.github.io/rx-book/content/mappingr_rxjs_from_different_libraries/async/index.html – xgrommx
@xgrommx謝謝!我在搜索前沒有找到這篇文章。會看看 – XeniaSis
再次感謝@xgrommx!它幫助我解決了這個問題:) – XeniaSis