1

I want to get downloadURL from this function. But, It doesn't wait to get it. So this function does not return downloadURL. How can I get it??

uploadProfileImage = async (uid, file) => {
        let userRef = this.str.ref(`${uid}`).child(`images/avatar.png`);

        const uploadTask = userRef.put(file);

        uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {

            let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log('Upload is ' + progress + '% done');
            switch (snapshot.state) {
                case firebase.storage.TaskState.PAUSED:
                    console.log('Upload is paused');
                    break;
                case firebase.storage.TaskState.RUNNING:
                    console.log('Upload is running');
                    break;

                default:
            }

        }, error => {
            console.log('[Error] ', error);
        }, async () => {
            const downloadUrl = await uploadTask.snapshot.ref.getDownloadURL()
            // update firebase database
            this.updateUserInfo(uid, { profileImage: downloadUrl });

        });

}
Noohone
  • 694
  • 5
  • 12
hyeongyuAn
  • 31
  • 2
  • You need to use `storageRef` to get the download url as show here https://firebase.google.com/docs/storage/web/download-files#create_a_reference – Panther May 30 '19 at 00:44
  • 'str' is storage in second line. This function is not wait to finish upload image in storage. So It donot return downloadURL – hyeongyuAn May 30 '19 at 00:57
  • Check this [post](https://stackoverflow.com/questions/5010288/how-to-make-a-function-wait-until-a-callback-has-been-called-using-node-js) probably is wait you are searching for. – Noohone May 30 '19 at 07:55

1 Answers1

0

One way of doing it is to simply follow up documentation provided by google here

uploadProfileImage = (uid, file) => {
    let userRef = this.str.ref(`${uid}`).child(`images/avatar.png`);

    const uploadTask = userRef.put(file);

    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {

        let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');
        switch (snapshot.state) {
            case firebase.storage.TaskState.PAUSED:
                console.log('Upload is paused');
                break;
            case firebase.storage.TaskState.RUNNING:
                console.log('Upload is running');
                break;

            default:
        }

    }, error => {
        console.log('[Error] ', error);
    }, () => {
        uploadTask.snapshot.ref.getDownloadURL().then((downloadUrl)=>{
        // update firebase database
        this.updateUserInfo(uid, { profileImage: downloadUrl });
        }
    });
}

I assume your variables are correct

delmin
  • 2,330
  • 5
  • 28
  • 54