简体   繁体   English

打字稿答应循环后返回

[英]typescript promise return after loop

I am trying to return after all the calls to an external service are done but my code is just flying through the for loop and returning. 在尝试完成对外部服务的所有调用后,我试图返回,但是我的代码只是通过for循环飞行并返回。 I cannot do a promise.all here as I need some values obtained in the loop. 我不能做一个promise.all,因为我需要在循环中获得一些值。 Is there an easy way to do this in typescript/angular2? 在typescript / angular2中有一种简单的方法吗?

var ret = [];
for (var l in users){
   var userLicense = users[l].licenseNumber;
   this.callExternalService(userLicense).subscribe(response=>{
      ret.push(response+userLicense);
   }
}
resolve(ret);

As you are already using observables, you can use a combination of forkJoin and map to achieve this: 由于您已经在使用可观察对象,因此可以结合使用forkJoinmap来实现:

var ret = [];
Observable.forkJoin(
    users.map(
        user => this.callExternalService(user.licenseNumber)
            .map(response => response + user.licenseNumber)
    )
).subscribe(values => {
    ret = values;
    resolve(ret);
})

You could try combineLatest : 您可以尝试combineLatest

return Observable.combineLatest(
  ...users.map(user => this.callExternalService(user.licenseNumber)
    .map(response => response + user.licenseNumber)),
  (...vals) => vals);

This will return an observable of arrays of results from the service calls, which you can then subscribe to, convert to a promise with toPromise if you prefer, etc. 这将从服务调用中返回可观察到的结果数组,然后您可以订阅这些结果,然后根据需要将其转换为toPromise的promise等。

if you need to do some aggregation in the loop and pass it as part of return, you can add it into a Promise.all as Promise.resolve(aggregatedData) 如果您需要在循环中进行一些汇总并将其作为返回的一部分传递,则可以将其作为Promise.resolve(aggregatedData)添加到Promise.all中。

Something like that: 像这样:

 function getData(ii) {
    return new Promise(res => {
      res(ii); 
     });
   }

 function getUserData(users) {
   let promiseArray = [];
   let aggregatedData = 0;

    users.forEach(user => {
      aggregatedData += user.id;
      promiseArray.push(getData(user.id));
    });
    promiseArray.push(Promise.resolve(aggregatedData));
    return Promise.all(promiseArray);
 }

 getUserData([{id:1}, {id:2}, {id:3}]).then(x=>console.log(x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM