angular - 如何在执行其他代码行之前等到异步函数完成
问题描述
我有一个上传图片的功能。我将代码放在某个服务文件中,并在另一个调用该服务的组件中调用它。我想在上传成功后调用服务的组件中执行另一行代码。
我已经阅读了另一个类似的问题。但是,我无法清楚地捕捉到答案,因为在另一个问题中,异步函数和之后的函数位于同一个文件中。我有一些线索Promise
和Observable
。但我不太了解如何正确使用它
这是我的服务:
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 */
}
我怎样才能做到这一点?
解决方案
推荐阅读
- java - 为什么 array.sorts 对父数组进行排序?
- javascript - 如何同步调用异步 JavaScript 函数?
- ssh - CP 脚本混淆文件名
- asp.net-core - .NET CORE 2.0 尝试激活时无法解析服务类型
- python - Selenium 加载时间错误 - 寻找可能的解决方法
- java - 如何将发件人的消息放在左侧,将收件人的消息放在右侧
- reactjs - 我正在尝试在 React js 中创建一个 onDimiss 按钮
- go - Kafka 消息未传递给消费者
- c# - Xamarin - 智能手机内存中的存储数据
- php - laravel 属于不使用一对一关系