NodeJS 我不明白如何在Angular文件上传中使用javascript/await [重复]

1cklez4t  于 5个月前  发布在  Node.js
关注(0)|答案(1)|浏览(76)

此问题在此处已有答案

async/await implicitly returns promise?(5个答案)
async/await always returns promise(5个回答)
3天前关闭。
我正在使用Angular + Firebase作为一个简单的Web应用程序。我有这个功能:

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

字符串
我想在Firebase中上传一个文件,并在上传后返回图像的字符串路径(即公共URL)。
问题是getDownloadURL(fileRef)返回一个Promise而不是一个字符串,而我无论如何也不知道如何等待并将promise解压缩为一个字符串,这样uploadFile就可以返回一个字符串值而不是一个promise!
我尝试使用await关键字,但编译器仍然说它返回一个Promise!那还有什么意义呢?
编辑:这是我使用uploadFile的方式:

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


编辑#2:我想明白了。让所有函数异步工作:

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


P.S.我不知道为什么我的问题被标记为关闭,因为我没有在类似的问题中找到答案,但好吧。

vwoqyblh

vwoqyblh1#

如何调用uploadFile函数?重要的是要记住,因为它是一个pixelc函数,它总是返回一个Promise。
与其在uploadFile函数中使用.then()方法,你可以考虑直接返回等待的Promise的结果。这种方法通过更有效地利用masc/await语法来简化函数。
它可以看起来像这样:

private async uploadFile(...): Promise<string> {
  // ...
  // Wait to get the URL
  return await getDownloadURL(fileRef);
}

字符串
记住,当你在代码中的其他地方调用这个uploadFile函数时,你必须处理返回的Promise。

相关问题