异步/等待uploadTask

时间:2018-11-05 14:15:00

标签: javascript firebase google-cloud-firestore firebase-storage

如何等待上载任务,以便在将下载网址和文档插入Firestore之前先上传图像/文件并跟踪其进度,

以下代码是我的示例Vue项目。它可以正常工作,但是请注意if (portraitFile),它必须在必须上传图像的条件下,如果我不想上传图像怎么办?

它必须移出该条件if,但是它将在文件完成并下载URL之前异步执行。

目标:将firestore add()移动到uploadTask的完成回调/参数之外。

    async commitCharacter() {
      try {
        let character = this.character;
        let portraitFile = this.portraitFile;

        if (portraitFile) {
          const uploadTask = storageRef
            .child(`characters/${character.id}/portrait.png`)
            .put(portraitFile, { contentType: "image/png" });

          await uploadTask.on(
            "state_changed",
            snapshot => {
              this.portraitUploadProgress =
                (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            },
            null,
            async () => {
              character.portraitUrl = await storageRef
                .child(`characters/${character.id}/portrait.png`)
                .getDownloadURL();

              if (character.id) {
              await db
                .collection("characters")
                .doc(character.id)
                .update(character);
              } else {
                character.id = (await 
                db.collection("characters").add(character)).id;
              }

              $("#manageCharacter").modal("hide");
            }
          );
        }
      }

1 个答案:

答案 0 :(得分:0)

您可以将uploadTask包裹在诺言中:

async function uploadTaskPromise() {
  return new Promise(function(resolve, reject) {
    const storageRef = storage.ref(YOUR_STORAGE_PATH)
    const uploadTask = storageRef.put(YOUR_FILE_OR_BLOB)
    uploadTask.on('state_changed',
      function(snapshot) {
        var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        console.log('Upload is ' + progress + '% done')
      },
      function error(err) {
        console.log('error', err)
        reject()
      },
      function complete() {
        task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
          resolve(downloadURL)
        })
      }
    )
  })
}

然后像这样使用它:

const storageUrl = await uploadTaskPromise()
console.log(storageUrl) // do whatever you want with the URL...