首页 > 解决方案 > 如何在执行其他代码行之前等到异步函数完成

问题描述

我有一个上传图片的功能。我将代码放在某个服务文件中,并在另一个调用该服务的组件中调用它。我想在上传成功后调用服务的组件中执行另一行代码。

我已经阅读了另一个类似的问题。但是,我无法清楚地捕捉到答案,因为在另一个问题中,异步函数和之后的函数位于同一个文件中。我有一些线索PromiseObservable。但我不太了解如何正确使用它

这是我的服务:

public changeImage = (e: any, prevImage: string, filePath: string) => {
    const file  = e.target.files[0];
    const ref   = this.storage.ref(filePath);
    const task  = this.storage.upload(filePath, file);

    this.uploadPercent = task.percentageChanges();
    task.snapshotChanges().pipe(
      finalize(() => console.log(`Finished`) )
    ).subscribe();
}

这是调用服务的组件:

public uploadImage = async (e: any) => {
    this.uploading        = true;
    await this.imageStorage.changeImage(e, this.admin.adminImage, `admin/${e.target.files[0].name}`);
    /* I want to execute code here after upload is success */
    this.uploading = false; /* executed after upload finished */
}

我怎样才能做到这一点?

标签: angularangularfire2

解决方案


推荐阅读