简体   繁体   English

Angular Http forEach 中的请求,等待完成请求直到继续循环

[英]Angular Http Request in forEach, wait to finish request until continue looping

I am looping through selected files, in order to first get a signed url and then put it directly to a S3 bucket.我正在遍历选定的文件,以便首先获得签名的 url,然后将其直接放入 S3 存储桶。 My Problem now is, that I want to wait until everything inside the forEach has finished, and then continue looping.我现在的问题是,我想等到 forEach 中的所有内容都完成,然后继续循环。

What I am experiencing now is that the code directly queries for a signed url for each file at the same moment.我现在遇到的是代码同时直接查询每个文件的签名 url。

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

I presume the observable from getSignedURL() is converted to a promise using toPromise() .我假设getSignedURL()的 observable 使用toPromise()转换为 promise 。 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.然后,您可以使用Array#map将数组中的元素 map 到可观察对象,使用 RxJS from function 以及concatMap运算符依次触发这两个元素的请求。

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 => { }
});

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

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