【问题标题】:assign download url to variable firestore [duplicate]将下载网址分配给变量firestore [重复]
【发布时间】:2020-08-19 23:21:27
【问题描述】:

我正在尝试将下载 url 分配给一个变量,但它没有应用它。该变量在函数之外,所以不确定我哪里出错了。我本质上想要下载 url 字符串,所以我可以将其用作参考。

var img_path;
var upload_path;
if (img.length != 0){
                var imageFile = img[0];
                var imageName = imageFile.name;

              
                img_path = ‘/some-path/’ + imageName;
                //upload image
                let storageRef = firebase.storage().ref(img_path);
                storageRef.put(imageFile).then((savedPicture) => {

                storageRef.getDownloadURL().then(function(downloadURL) {
                  console.log('File available at', downloadURL);
                  upload_path = downloadURL;
                });

    });
//returns undefined
console.log(upload_path);

【问题讨论】:

    标签: javascript firebase firebase-storage


    【解决方案1】:

    确定下载 URL 是一个异步操作。

    当您的console.log(upload_path) 运行时,upload_path = downloadURL 尚未运行。您可以通过在这些行上放置断点并在调试器中运行,或者通过检查日志输出的顺序来最轻松地验证这一点。

    任何需要下载 URL 的代码都需要在该 URL 可用时调用的回调中,或者从那里调用。

    所以最简单的解决方法是将需要下载 URL 的代码移动到回调中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 2019-01-16
      相关资源
      最近更新 更多