首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将异步转换为Rx.js

将异步转换为Rx.js
EN

Stack Overflow用户
提问于 2016-03-07 16:43:16
回答 1查看 131关注 0票数 0

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

代码语言:javascript
复制
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错误。

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

代码语言:javascript
复制
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,所以如果有任何帮助,我们将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2016-03-07 22:55:21

将记录器列表转换为可观察的流,然后对每个记录器执行flatMap (即执行异步处理),然后调用toArray将所有结果存储到一个数组中,这可能会更容易:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35839415

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档