Upload the additional data only when the image upload is finished (sequence?)


#1

I have a problem with the code below. I am taking a photo with the camera then uploading the image to the firebase storage. However i am adding additional data too to the database and it is containing the photo url too. The script above start uploading the image to the storage but the other part of the code won’t work because the this.picurl will have value only after the upload process is finished.

How could i add a sequence so when the this.picurl=savepic.downloadURL finally available (image upload successful), rest of the code will run.

  adatfeltolt() {
    this.mypicref.child(this.uid()).child('pic.jpg')
    .putString(this.picdata, 'base64', { contentType: 'image/jpg' })
    .then(savepic => {
      this.picurl = savepic.downloadURL
    })
      this.firebasedb.list("/fogasok/").push({
      datum:this.fogasDatuma,
      //halfaj:this.fogasHalfaj,
      suly:this.fogasSuly,
      egyeb:this.fogasEgyeb,
      keplink:this.picurl
    });

  }

#2

Move the second call to inside the .then() function:

adatfeltolt() {
  this.mypicref.child(this.uid()).child('pic.jpg')
  .putString(this.picdata, 'base64', { contentType: 'image/jpg' })
  .then(savepic => {
    
    this.firebasedb.list("/fogasok/").push({
      datum:this.fogasDatuma,
      //halfaj:this.fogasHalfaj,
      suly:this.fogasSuly,
      egyeb:this.fogasEgyeb,
      keplink:savepic.downloadURL
    });
  })

}

Remember, almost EVERYTHING in JavaScript is asynchronous. I’m also doing some test migrating my stuff to async/await, worth the try, it’s a bit like this:

async adatfeltolt() {
  const savedPic = await  this.mypicref.child(this.uid()).child('pic.jpg')
    .putString(this.picdata, 'base64', { contentType: 'image/jpg' });

    this.firebasedb.list("/fogasok/")
    .push({
      datum:this.fogasDatuma,
      //halfaj:this.fogasHalfaj,
      suly:this.fogasSuly,
      egyeb:this.fogasEgyeb,
      keplink: savedPic.downloadURL
    });
}

Basically the await is telling it to wait until that is ready to move to the next line.