本文介绍了异步/等待uploadTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I await uploadTask so I can upload the image/file and track its progress first before inserting download url dan document to firestore,

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

Following code is my sample Vue project. It works properly, but see the if (portraitFile), it has to be within the condition that I have to upload an image, what if I don't want to upload an image?

它必须移出条件 if ,但是它将在文件完成和下载URL检索之前异步执行.

It has to move outside that conditional if, but it will executed asynchronously before the file finish and download URL retrieved.

目标:将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");
            }
          );
        }
      }

推荐答案

您可以将 uploadTask 包装在一个Promise中:

You can wrap your uploadTask in a promise:

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() {
        uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
          resolve(downloadURL)
        })
      }
    )
  })
}

然后像这样使用它:

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

这篇关于异步/等待uploadTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:33