使用Observable排队承诺

时间:2018-04-16 12:50:33

标签: javascript angular rxjs observable

我有一连串的承诺,我不希望他们开始,直到所有先前的承诺得到解决,但同时使用了Observables。

我尝试这样的事情:

    if let json = response.result.value as? [String: Any], let arr = json["restaurants"] as? [[String: Any]] {
        let RestaurantArray: [[String: Any]] = arr

        for dict in RestaurantArray {
            if let picture = dict["restaurantPicture"] as? String,
                let name = dict["restaurantName"] as? String,
                let status = dict["status"] as? String {

                let restaurantModal: Restaurant = Restaurant( restaurantPicture: picture, restaurantName: name, status: status)
                self.restaurant.append(restaurantModal)
            }
        }

        // Reload table view on main thread (UI related update)
        DispatchQueue.main.async {
            self.tableViewRestaurants.reloadData()
        }
    }

2 个答案:

答案 0 :(得分:1)

那只是concatMap运营商。唯一的问题是你在哪里创建Promises:

const queue = Rx.Observable.create();
const results = queue.concatMap(p => createPromise(p));

results.subscribe(console.log);

queue.add(getNewObservable(...));
queue.add(getNewObservable(...));
queue.add(getNewObservable(...));

答案 1 :(得分:0)

使用concat运算符。

import { Component } from '@angular/core';
import { concat } from 'rxjs/observable/concat';
import { fromPromise } from 'rxjs/observable/fromPromise';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    const p1 = Promise.resolve(1);
    const p2 = Promise.resolve(2);
    const p3 = Promise.resolve(3);

    const o1 = fromPromise(p1);
    const o2 = fromPromise(p2);
    const o3 = fromPromise(p3);

    concat(o1, o2, o3)
      .subscribe(console.log)
      // logs 1, 2, 3
  }
}

Live demo