0

I am looping through selected files, in order to first get a signed url and then put it directly to a S3 bucket. My Problem now is, that I want to wait until everything inside the forEach has finished, and then continue looping.

What I am experiencing now is that the code directly queries for a signed url for each file at the same moment.

Thanks for any help

result['files'].forEach(file => {
    this.fileService.getSignedURL(this.vehicleId, file.name, file.type, file.size)
       .then(res => {
          this.pushFile(file, app, description, languageKey, file.name, res.path, res.signed_url)
       });
});
kevla
  • 21
  • 3
  • Does this answer your question? [How to use promise in forEach loop of array to populate an object](https://stackoverflow.com/questions/38362231/how-to-use-promise-in-foreach-loop-of-array-to-populate-an-object) – jonrsharpe Mar 05 '21 at 10:08
  • I am still facing the issue with using Promise.all – kevla Mar 05 '21 at 10:24
  • I am not understanding the question correctly. So you wish to fetch the url and push the file for each file sequentially? – ruth Mar 05 '21 at 10:34
  • Maybe for-await-of loop? e.g. https://stackoverflow.com/a/50874507/12249019 – yh6 Mar 05 '21 at 10:36
  • Yes, this is exactly what I would like to do file[0] --> get signed Url --> put file --> file[1] --> get signed Url --> put file --> file [2] --> ... – kevla Mar 05 '21 at 10:38

1 Answers1

1

I presume the observable from getSignedURL() is converted to a promise using toPromise(). If so remove it and return it as an observable.

Then you could map the elements in the array to the observable using Array#map, use RxJS from function along with concatMap operator to trigger both the requests for the elements sequentially.

Try the following

from(
  result['files'].map((file) =>
    this.fileService.getSignedURL(this.vehicleId, file.name, file.type, file.size).pipe(
      concatMap((res) => 
        this.pushFile(file, app, description, languageKey, file.name, res.path, res.signed_url)
      )
    )
  )
).subscribe({
  next: res => { },
  error: error => { }
});
ruth
  • 29,535
  • 4
  • 30
  • 57