2016-10-04 147 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示例中的注释代码还显示了每个承诺可以单独解决,并在承诺的顺序不重要时合并回原始流。

相关问题