我的 firebase 存储函数不允许我从函数中获取 url

My firebase storage function doesnt let me take the url from the function

我是编程新手,我对这个错误感到很困惑,因为我想下载 link 到一个数组中,但它 returns 我是空的,但是当我执行它时console.log 在 .then 它 returns 我 link 但如果我在 returns 之外做我什么都没有 :(

 var title = "";
 var price = "";
 var description = "";
 var image = new Array();


firebase
.database()
.ref("/productos/" + itemId)
.on("value", (snapshot) => {
  title = snapshot.val().title;
  price = snapshot.val().price;
  description = snapshot.val().description;
});


firebase
    .storage()
    .ref("/images/" + itemId)
    .getDownloadURL()
    .then((url) => {
      image = [url];
      console.log(image)      
      setLoading(false);
    })
    .catch((error) => {
      console.log(error);
    });
    console.log(image)

我认为您需要研究一下 promises 的工作原理,这样您才能了解发生了什么。您的代码看起来不错,但说实话有点乱,也许下面使用 async/await 而不是 promise 链可以帮助您。我只是创建这个函数来模拟逻辑的工作方式,而不是因为它会有用。

// Global array variable image
const image = new Array();
const itemId = 'an_id';

const addItemDownloadUrlToArray = async (ref) => {
  // Use async await not promise chaining
  const url = await firebase.storage().ref(ref).getDownloadURL();
  image.push(url);
};

// After this has run, image will have the url in it
addItemDownloadUrlToArray(`/images/${itemId}`);