Angular+Firebase文件上传中async/await使用及返回值问题求助
Angular + Firebase异步上传文件无法获取正确URL的问题与解决
问题描述
使用Angular + Firebase开发Web应用时,编写了异步上传函数,期望上传文件到Firebase后返回图片公开URL字符串,但getDownloadURL(fileRef)返回Promise,即便使用await,编译器仍提示函数返回Promise,无法获取正确的字符串值。
原上传函数代码
private async uploadFile(id: number, filePath: string, name: string, input: HTMLInputElement) : Promise<string> { const ext = filePath.split('.').pop(); const path = '/' + id + '/' + name + '.' + ext const fileRef = ref(this.firebaseStorage, path); await uploadBytesResumable(fileRef, input.files[0]); let url: string = ''; await getDownloadURL(fileRef).then((result: string) => { url = result; }); console.log(url); return url; }
原调用代码
if (thumbnailStr != '') { thumbnailStr = this.uploadFile(id, this.blogForm.get('thumbnail').value, 'thumbnail', thumbnailImg); } if (backgroundStr != '') { backgroundStr = this.uploadFile(id, this.blogForm.get('background').value, 'background', backgroundImg); } console.log('url:', thumbnailStr); const blog = { 'id': id, 'blogDate': datetime, 'heading': this.blogForm.get('heading').value, 'subHeading': this.blogForm.get('subHeading').value, 'blogDetail': this.blogForm.get('blogDetail').value, 'thumbnail': thumbnailStr, 'background': backgroundStr }; this.blogs_service.addBlog(blog);
问题原因
- 上传函数中对
getDownloadURL同时使用await和.then()的写法冗余,且没有直接返回Promise解析后的结果; - 调用
uploadFile时未添加await关键字,导致变量直接接收了Promise对象,而非解析完成的URL字符串。
解决方案
将所有涉及异步调用的函数标记为async,并在调用异步函数时使用await等待Promise解析:
修改后的上传函数
private async uploadFile(id: number, filePath: string, name: string, input: HTMLInputElement) : Promise<string> { const ext = filePath.split('.').pop(); const path = '/' + id + '/' + name + '.' + ext const fileRef = ref(this.firebaseStorage, path); await uploadBytesResumable(fileRef, input.files[0]); return await getDownloadURL(fileRef); }
修改后的调用函数
async addPost(thumbnailImg: HTMLInputElement, backgroundImg: HTMLInputElement) { // ... 其他业务逻辑 if (thumbnailStr != '') { thumbnailStr = await this.uploadFile(id, this.blogForm.get('thumbnail').value, 'thumbnail', thumbnailImg); } if (backgroundStr != '') { backgroundStr = await this.uploadFile(id, this.blogForm.get('background').value, 'background', backgroundImg); } // ... 后续创建blog对象并调用服务的逻辑 }
说明
修改后,await会等待uploadFile的Promise完成解析,将实际的URL字符串赋值给变量,后续创建blog对象时就能正确传入图片URL。
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

