如何等待Firebase存储映像上传,然后运行下一个功能

问题描述 投票:0回答:1

[我正在尝试编写一个函数,将多个图像上传到Firebase,保存返回给对象的URL,然后将该对象上传到我的Cloud Firestore。我对异步/等待或诺言没有真正的了解,因此,如果有人可以提供帮助,将不胜感激。

[基本上,我希望uploadImages()完成运行后再运行uploadData(),在提交表单时会触发saveIssue()

这是我正在使用的东西:

saveIssue() {
  this.uploadImages();
  this.uploadData();
},
uploadData() {
  let self = this;
  db.collection("issues")
    .add(self.issue)
    .then(docRef => {
      self.$router.push({
        name: "ReportPage",
        params: { issueId: docRef.id }
      });
    })
    .catch(error => {
      console.error(error);
    });
},
uploadImages() {
  const storageRef = storage.ref();
  let self = this;
  this.imagePreviews.forEach(image => {
    let imageName = uuidv1();
    let fileExt = image.fileName.split(".").pop();
    let uploadTask = storageRef
      .child(`images/${imageName}.${fileExt}`)
      .putString(image.base64String, "data_url");
    uploadTask.on("state_changed", {
      error: error => {
        console.error(error);
      },
      complete: () => {
        uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
          self.issue.images.push(downloadURL);
        });
      }
    });
  });
},
javascript firebase vue.js promise firebase-storage
1个回答
0
投票

您必须使用诺言,如here所述。您可以重写代码以支持异步等待,因为firebase开箱即用地支持它,但是对于开始,它可以像这样:

async saveIssue() {
    await this.uploadImages();
    await this.uploadData();
  },
  uploadData() {
    return new Promise((resolve, reject) => {
      let self = this;
      db.collection("issues")
        .add(self.issue)
        .then(docRef => {
          self.$router.push({
            name: "ReportPage",
            params: {
              issueId: docRef.id
            }
          });
          resolve();
        })
        .catch(error => {
          console.error(error);
          reject(error);
        });
    })
  },
  uploadImages() {
    return new Promise((resolve, reject) => {
      const storageRef = storage.ref();
      let self = this;
      this.imagePreviews.forEach(image => {
        let imageName = uuidv1();
        let fileExt = image.fileName.split(".").pop();
        let uploadTask = storageRef
          .child(`images/${imageName}.${fileExt}`)
          .putString(image.base64String, "data_url");
        uploadTask.on("state_changed", {
          error: error => {
            console.error(error);
            reject(error);
          },
          complete: () => {
            uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
              self.issue.images.push(downloadURL);
              resolve();
            });
          }
        });
      });
    })
  },
© www.soinside.com 2019 - 2024. All rights reserved.