简体   繁体   中英

firebase.storage().ref().getDownloadURL() won't run

I am trying to upload an image to Firebase Storage and save the downloadURL in Firestore, but when my code is running, .getDownloadURL() won't run. The image uploads, but after that, nothing happens. My code is below. I've tried with several images.

const task = firebase.storage().ref('/hendingar/' + img.name).put(img)

task.then((snapshot) => {
  console.log('Img ')
  snapshot.ref.getDownloadURL((url) => {
    console.log('Url')
    firebase.firestore().collection('hendingar').add({
      title: title,
      description: description,
      start: start,
      end: end,
      place: infoPlace,
      prices: temp_arr,
      img: url,
    }).then(() => {
      console.log('Success')
    }).catch((error) => {
      console.error(error)
    })
  })
})

You're not getting any results or logs after console.log('Img ') because you're not chaining the promise properly. You must call the getDownloadURL() before chaining .then() . See code below:

const task = firebase.storage().ref('/hendingar/' + img.name).put(img)

// Uploads the file to Firebase Storage.
task.then((snapshot) => {
  console.log('Img')
  // You can also put the creation of Firestore Document here.
  // (If you want it to create the document before getting the download URL.)
  
 // Calls the `getDownloadURL()` method.
 snapshot.ref.getDownloadURL()
  .then((url) => {
    // Returns the Download URL from Firebase Storage.
    console.log('Url')
    console.log(url)
    
    // You can put this either here or before getting download URL.
    firebase.firestore().collection('hendingar').add({
      title: title,
      description: description,
      start: start,
      end: end,
      place: infoPlace,
      prices: temp_arr,
      img: url,
    }).then(() => {
      console.log('Success')
    }).catch((error) => {
      console.error(error)
    })
  })
})
.catch((error) => {
  // Logs error if there's an error uploading of file.
  console.log(error)
})

I leave some comments on the code above for better understanding. For more information, you may checkout this documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM