getDownloadURL() 返回变量的未定义结果



>我想从她那里使用(getDownloadURL(的"url", 可能,在这样的变量中。但是 this.url 返回的所有内容都是未定义的结果。 (我已经与Firebase和import等建立了所有连接( 有谁知道是否有办法做到这一点? 提前谢谢。

正在运行的应用的示例图像

var storage = firebase.storage();
var storageRef = storage.ref();
const spaceRef = storageRef.child(`Profis/${this.EMAIL}.png`);
spaceRef.getDownloadURL().then(function(url){this.url = url})

console.log("teste: " + this.url);

当您调用getDownloadURL时,下载网址会异步加载到 Firebase 服务器。由于这可能需要一些时间,因此该调用的代码会立即继续。然后,当下载网址从服务器返回时,Firebase 会调用您在then回调中指定的代码。

通过在代码中放置一些日志语句来最容易看到这一点:

var storage = firebase.storage();
var storageRef = storage.ref();
const spaceRef = storageRef.child(`Profis/${this.EMAIL}.png`);
console.log("Before calling getDownloadURL()");
spaceRef.getDownloadURL().then(function(url){
console.log("Got download URL");
});
console.log("After calling getDownloadURL()");

运行此代码时,输出为:

在调用 getDownloadURL(( 之前

调用 getDownloadURL(( 后

获得下载网址

这可能不是您所期望的。但它确实解释了为什么打印时testUrl未定义:该值尚未从服务器返回。

因此,所有需要下载 URL 的代码都需要在里面,然后then()回调(或从里面调用(。所以:

var storage = firebase.storage();
var storageRef = storage.ref();
const spaceRef = storageRef.child(`Profis/${this.EMAIL}.png`);
spaceRef.getDownloadURL().then(function(url){
this.url = url
console.log("teste: " + this.url);
});

顺便说一下,对于不熟悉调用异步 Web API 的开发人员来说,这是一个非常常见的混淆来源。由于许多 API 都是以这种方式运行的,我建议现在花一些时间研究它,这样你就不会那么频繁地对它感到困惑。一些来源:

  • 为什么在函数内部修改变量后,我的变量保持不变? - 异步代码参考
  • JavaScript 从回调返回(计时(将值分配给变量

最新更新