Jason
Jason

Reputation: 1141

Call inner function but wait for response before moving on

I have a function and inside that function I am running an inner function. I need to wait for the result of the inner function before moving on with the main function. I am still figuring out async and await.

here is my outer function with the inner function. the ... represent additional code:

async editSection () {
   ...
                
   if(this.file) {
       let uploadedFile = await this.uploadFile()
   }

    ....
}

here is the secondary function:

uploadFile() {  
            var splitfile = this.file.name.split('.')     
            var newname = splitfile[0] + '_' + Date.now() + '.' + splitfile[1]
            var storage = firebase.storage()
            storage.ref('xxxx/'+newname).put(this.file)
            .then(response => {
                return response.metadata.fullPath
            })
            .catch(err => {
                console.log(err)
                return err
            })
            
        },

Upvotes: 0

Views: 39

Answers (1)

Berk Kurkcuoglu
Berk Kurkcuoglu

Reputation: 1523

Just return your Promise from the inner function so await resolves(waits for) it.

uploadFile() {  
        var splitfile = this.file.name.split('.')     
        var newname = splitfile[0] + '_' + Date.now() + '.' + splitfile[1]
        var storage = firebase.storage()
        return storage.ref('xxxx/'+newname).put(this.file)
        .then(response => {
            return response.metadata.fullPath
        })
        .catch(err => {
            console.log(err)
            return err
        })
        
    },

Upvotes: 1

Related Questions