最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AsyncAwait uploadTask - Stack Overflow

programmeradmin5浏览0评论

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,

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?

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

GOAL: Move firestore add() outside uploadTask's finish callback/argument.

    async mitCharacter() {
      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");
            }
          );
        }
      }

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,

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?

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

GOAL: Move firestore add() outside uploadTask's finish callback/argument.

    async mitCharacter() {
      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");
            }
          );
        }
      }
Share Improve this question edited Nov 5, 2018 at 15:05 Frank van Puffelen 599k85 gold badges889 silver badges859 bronze badges asked Nov 5, 2018 at 14:14 Fransisco WijayaFransisco Wijaya 3974 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 21

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

And then use it like this:

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

评论列表(0)

  1. 暂无评论