Home > Enterprise >  I can´t Getting a value returned by a async function (firebase storage)
I can´t Getting a value returned by a async function (firebase storage)

Time:01-14

I am uploading photos to my firebase Storage, then I need to get the url of these photos to send them to a database. My "download" function should return the url, but there is no way I can get it. When I make a Console.log(url) at the end of my function I can see it by console, but when I try to replace it with a "return url" and try get it using "then" method in my main module or using "const url= await download()" always throws me undefined. I need to get the value and asign to a const o state.

It´s my download function, it´s part of my controller.js

export async function download (path){
    await getDownloadURL(ref(storage, path))
    .then((url) => {
        return (url);
    })
    .catch((error) => {

        switch (error.code) {
        case 'storage/object-not-found':
            console.log('storage/object-not-found')
            break;
        case 'storage/unauthorized':
            console.log('storage/unauthorized')
            break;
        case 'storage/canceled':
            console.log('storage/canceled')
            break;
        case 'storage/unknown':
            console.log("unknow")
            break;
    }
  })
}

So in one of my JSX files (react) where I have the buttons and inputs, I implement functions like these and I can't get the value in a var or a state, even console prints show me "undefined"

 function test() {
  download("/3.png").then(item => console.log(item))
}
async function test() {
  console.log(await download("/3.png"))
}
async function test() {
  const url = await download("/3.png")
}

CodePudding user response:

Ultimately, this is because you aren't returning a value from your function. Note how in your function, there is no return statement at the top level

export async function download (path) {
  await getDownloadURL(ref(storage, path))
    .then(/* ... */)
    .catch(/* ... */)
}

You need to return a value at the top level otherwise you will only get undefined:

export async function download (path) {
  // ⬇⬇⬇
  return getDownloadURL(ref(storage, path)) // removed await because it makes no difference here
    // .then(url => url) is pointless and should be removed
    .catch(/* ... */) 
}

Additionally, you should rethrow the exception in the catch handler or at least return null if you are intentionally suppressing it.

export async function download (path) {
  return getDownloadURL(ref(storage, path))
    .catch(err => {
      console.log("getDownloadURL failed: "   (err.code || "unknown"), err);
      return null; // suppress exception
    });
}
  • Related