【问题标题】:How to do async code synchronously Angular 5如何同步执行异步代码Angular 5
【发布时间】:2019-02-09 08:20:20
【问题描述】:

我有一个迭代文件列表的函数,然后对于每个文件,它调用一个异步方法,该方法执行一些图像操作,然后将图像推送到一个数组。

问题是异步调用同时发生,因此它锁定了 UI。所以我想遍历列表,但只在前一个完成时调用该函数。

Array.from(files).forEach(data => {
    if (data.size > 5000000) {
        this.toastr_service.error('FILE ' + data.name + ' EXCEEDS FILE SIZE LIMIT (5MB)');
    }else {
        this.asyncFunc(data).subscribe(result => {
            this._photos.push(result);
        }, error => {
            console.log(error);
        });
    }
});

【问题讨论】:

  • 请发布您的代码和(/或)minimal reproducible example 重现您的问题
  • 为什么不链接请求?
  • 使用 RxJS - 它可以很好地处理异步代码
  • 正如@mast3rd3mon 明智地建议的那样,您可能应该链接请求。由于您的应用程序似乎不能同步工作,因此您应该使用 fork join 进行链接。编辑:另外,不要忘记。 subscribe 方法还有一个“done”回调,您可以在其中应用仅应在成功完成任务时执行的逻辑。
  • @tricheriche 我已经添加了代码

标签: angular typescript asynchronous


【解决方案1】:

使用数组的map函数以及RxJS的forkJoin

forkJoin(Array
  .from(files)
  .map(file => file.size < 5000000 && this.asyncFunc(file) || undefined)
  .filter(value => !!value)
).subscribe(([...responses]) => {
  console.log(responses);
  this._photos.push(...responses);
});

forkJoin 将在文件大小低于 5Mb 的情况下进行所有调用(mapfilter 负责处理),一旦进行所有调用,响应将被推送到您的数组中。

编辑如果您希望对您的呼叫进行排序,请改用concat

concat(...Array
  .from(files)
  .map(file => file.size < 5000000 && this.asyncFunc(file) || undefined)
  .filter(value => !!value)
).subscribe((...responses) => {
  this._photos.push(...responses);
  console.log(this.photos);
});

【讨论】:

  • 它似乎什么也没做
  • 我的错,我颠倒了条件......它正在寻找大小超过 5Mb 的文件!
  • @user3074140 我编辑了我的答案,请随意尝试
  • 感谢您的帮助。我似乎仍然没有得到 console.log 我的代码对于一个图像来说很好,但多个会导致 ui 问题。这段代码是否一个接一个地运行异步函数,因为这是我想要实现的。我尝试了您更新的代码,用户界面似乎以同样的方式锁定。
  • HTTP 调用是异步的。您的用户界面不能被它阻止,或者如果它被阻止,那是因为其他原因。 This working stackblitz 表明它确实有效,如果您想知道的话。
【解决方案2】:

测试这个解决方案?

Array.from(files).flatMap(async data => {
  const result = await asyncFunc(data);
  this._photos.push(result);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    相关资源
    最近更新 更多