【问题标题】:Firebase getDownloadURL() not updating global variable [duplicate]Firebase getDownloadURL()不更新全局变量[重复]
【发布时间】:2020-05-28 05:48:05
【问题描述】:
我有以下脚本
let link = ""
let baseUrl = "Test-Dataset/"
let imageRef = "2.jpg"
storage.ref(baseUrl + imageRef).getDownloadURL().then(
function(url) {
link = url
console.log(url)
}).catch(function(error) {
});
console.log(link)
我的目标是在我使用getDownloadURL() 返回一个承诺并等待它得到解决之后,用图像 URL 的值更新link 变量。 .this() 中的 console.log 函数正在输出我需要的内容 - 指向我的 firebase 存储中图像的链接。但是,函数外部的console.log 在调用我的firebase 存储之前返回link 的初始值,即""。为什么会这样?我的解决方案是制作类似于https://stackoverflow.com/a/53578626/8849802 中概述的异步函数吗?
详情:我正在使用 vue 和 npm 库firebase
【问题讨论】:
标签:
javascript
firebase-storage
【解决方案1】:
发生这种情况是因为您的控制台语句在承诺解决之前运行。它与 Firebase 无关。
会发生这样的事情:
-
link 变量用空字符串声明。
- 在 Promise 中添加了一个处理函数:
.then(function(url) { ... } )
-
console.log(link) 输出 link 的值,它仍然是一个空字符串
- promise 解析并将
link 设置为url。
尝试在代码的最后添加此代码以更清楚地查看效果:
setTimeout(() => {
console.log(link);
}, 1000);
这将在 1 秒后输出 link 的值。它的值应该是你想要的 URL。
要解决这个问题,你可以使用 async/await。
const getLink = async (ref) => {
const url = await storage.ref(ref).getDownloadURL();
return url;
}
// NB: A function that uses `await` must be `async`
// So, whichever function uses getLink() must be async
function async someFunction() { // Maybe a Vue method?
const url = await getLink(baseUrl + imageRef);
console.log(url);
}
要添加错误处理,请使用 try/catch 块:
function async someFunction() {
try {
const url = await storage.ref(baseUrl + imageRef).getDownloadURL();
console.log(url); // This won't run if getting the URL failed
} catch (error) {
// Handle the error
}
}