简体   繁体   中英

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. I cannot do a promise.all here as I need some values obtained in the loop. Is there an easy way to do this in 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:

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 :

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.

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)

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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