2016-10-04 153 views
0

我需要進行多個依賴於對方的異步調用。我最初編寫代碼並使用Promise.all分步製作async。我繞過了我的數據並創建了一個async方法,以便將所有需要的操作放入一個數組中傳遞到Promise.all()。這工作正常,但我怎麼能使用Observables來做同樣的事情。我讀過forkJoin相當於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示例中的註釋代碼還顯示了每個承諾可以單獨解決,並在承諾的順序不重要時合併回原始流。

相關問題