Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将async转换为Rx.js_Javascript_Mongodb_Rxjs - Fatal编程技术网

Javascript 将async转换为Rx.js

Javascript 将async转换为Rx.js,javascript,mongodb,rxjs,Javascript,Mongodb,Rxjs,因此,我们正在尝试将我们的express服务器重写为Rx。它目前正在对所有流操作使用async。代码如下所示: var async = require('async'); function getCountAndChannels(name, cb){ var tasks = [ function(cb) { //does a mongoDB search and returns count }, function

因此,我们正在尝试将我们的
express
服务器重写为
Rx
。它目前正在对所有流操作使用
async
。代码如下所示:

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');
});
这里我要做的是循环遍历
记录器的数组
,并为每个记录器计算两个mongoDB搜索。我尝试过使用
Rx.Observable.merge
,它不在数组中返回结果,而是在回调的两个不同调用中返回结果。于是,我尝试了
Rx.Observable.zip
,我相信这就是我要找的

问题是我不知道如何循环
记录器
并在所有操作完成后发送结果。因为一个简单的
forEach
循环将在发送头后抛出一个
无法设置头的错误

这就是我到目前为止所做的:

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,因此非常感谢您的帮助。

将您的记录器列表转换为可观察的流,然后在每个记录器上执行
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;
});

Rx@xgrommx中的async.js提供了大量可选操作符,谢谢!我以前在搜索时没有找到这篇文章。我会再看一眼谢谢@xgrommx!它帮助我解决了问题:)谢谢,已经解决了,但我也会尝试你的解决方案。