2016-10-04 5 views
0

お互いに依存するいくつかの非同期呼び出しを行う必要があります。私は最初にコードを書いてPromise.allを使用してasyncを段階的に作成しました。私はデータをループし、Promise.all()に渡すために必要なアクションをすべて配列に入れるためにasyncメソッドを作成しました。これは正常に動作しますが、Observablesを使用して同じことをどうすればできますか。私はがPromise.allと同じだと読んだことがありますが、データをループしてasync関数をラップしてから、次のflatMapに移動する前にそれを実行できますか?Promise.allをObservableに変換する

public getMonthly(){ 
return this.http.get(url) 
      .flatMap(response => { 
       // need to convert this? 
       let actions = response.json().map(this.asyncMonthlyRecord); 
       return Promise.all(actions); 
      }) 
      .flatMap(()=> this.queryMonthly()) 
      .map(this.convertFromSQl) 
      .catch((error:any)=> Observable.throw(error || 'Server Error')); 
} 

private asyncMonthlyRecord = (record):Promise<any> => { 
     return this.setUsage(record,'HILowMonthly'); 
} 

private queryMonthly(){ 
     return this.storage.query('SELECT * FROM HILowMonthly') 
} 

getMonthly().subscribe(x => console.info(x)); // logs data from SQLite perfectly... 
+0

なぜ賛成ですか? – inspired

答えて

0

私が何をしたいことは約束は任意の順序で解決が、正しい順序で返されていることを、この

Rx.Observable.of({ itemIds: [1, 2, 3, 4, 5 ]}) 
    .mergeMap(response => { 
    const promises = response.itemIds 
     .map(id => { 
     return new Promise((resolve, reject) => { 
      // Wait for some random time, then resolve the promise. 
      const timeout = Math.floor(Math.random() * 5000); 
      setTimeout(() => { 
      console.log(`Finished promise ${id}`); // debug only 
      resolve({id, resolved: true}) 
      }, timeout); 
     }); 
     }); 
    // Wait until all Promises have been resolved, then return all 
    // of them in a single and ordered array. 
    return Rx.Observable.forkJoin(promises); 
    }) 
    .subscribe(x => console.log(x)); 

Working code on jsbin

お知らせのようなものだと思います。 jsbinの例のコメント付きコードは、約束の順序が重要でない場合には、個々の約定を個別に解決して元のストリームに戻すこともできることを示しています。

関連する問題