并行运行异步任务 [英] Running async tasks in parallel

查看:99
本文介绍了并行运行异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在RxJS中,当您想要按顺序运行http请求时 - 将它们链接起来。但我不清楚如何并行运行请求?我在 http://reactive-extensions.github.io/learnrx/ 的示例中看到了他们使用Observable.zip()并行运行2个请求。但是你如何并行运行5个请求呢?
更具体地说,我如何设置以便调用我的函数:

In RxJS, when you want to run http requests in sequence- you chain them. But I'm not clear on how can I run requests in parallel? I saw in the examples on http://reactive-extensions.github.io/learnrx/ that they use Observable.zip() to run 2 requests in parallel. But how would you run 5 requests in parallel? More specifically, how can I setup so that my function is called:


  • 当所有5个完成时?

  • 首次完成时?

推荐答案

这是一个很老的问题,但是没有接受的答案。您正在寻找的答案可能非常简单: concatMap

This is a quite old question but without an accepted answer. The answer you are looking for might be surprisingly simple: concatMap.

创建承诺后,它立即开始执行,因此它们并行执行;当从一个observable发出值时,它们是串行的。

When a promise is created, it starts execution immediately, so they are executing in parallel; while when values are emitted from one observable, they are in serial.

因此结合这两个,对于下面的代码片段,来自promise的observables是并行执行的,它们的结果是串行发出的,因为concatMap按照它们的创建顺序将它们放入一个流中。

So combine these two, for the following code snippet, observables from promise are executed in parallel, and the result of them are emitted in serial because concatMap puts them into one stream in the order they are created.

Rx.Observable.from(urls_array)
.concatMap(function(url) { return Rx.Observable.fromPromise(Promise.resolve($.get(url))) })
.subscribe(
  function(jsonObj) {
    // first result will arrive first
  },
  function(err) { },
  function() {
    // all completed
  }
)

这篇关于并行运行异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆