我正在处理存储firebase,我正在尝试获取URL并将其设置为变量,遗憾的是我无法做到这一点,我的代码出了问题。有人可以帮帮我吗?
这是错误:
firebase.js:1未捕获(在promise中)错误:Reference.push失败:第一个参数在属性'PostUsers.ImageURL.i'中包含未定义
这是代码:
console.log('Nice, The file has been successfully uploaded to the Firebase storage!');
var DownloadURL = uploadTask.snapshot.downloadURL;
var Url_File = uploadTask.snapshot.ref.getDownloadURL().then(function (URL) {
return URL;
});
alert(Url_File);
uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
console.log('File available at', downloadURL);
//Url_File = downloadURL;
});
//getting the publication time
var dayObj = new Date();
var day = dayObj.getDate();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var month = monthNames[dayObj.getMonth()]
var year = dayObj.getFullYear();
var hour = dayObj.getHours();
var minutes = dayObj.getMinutes();
var seconds = dayObj.getSeconds();
var GlobalUserName = <%=Session["UserId"] %>;
firebase.database().ref('PostUsers/').push({
ImageURL: Url_File,
userAuthor: GlobalUserName,
day: day,
month: month,
year: year,
hour: hour,
minutes: minutes,
seconds: seconds
});
//console.log('the download Url of your file is: '+ downloadURL);
console.log('User post successfully added to realtime data bases');
});
我尝试过许多不同的方法,但是没有一种方法能正常运作。
提前谢谢。答案 0 :(得分:2)
在这段代码中:
var Url_File = uploadTask.snapshot.ref.getDownloadURL().then(function (URL) {
return URL;
});
下载URL位于名为URL
的变量的promise回调中。它不在Url_File
。 Url_File
将包含then()
返回的承诺。
您需要将使用下载URL的代码放在首次可用的promise回调中。现在的方式是,在URL可用之前,正在执行使用下载URL的代码。
答案 1 :(得分:2)
下载网址仅适用于您从then
获得的getDownloadURL()
回调。你不能在那之外访问它。
因此,解决方案是将需要下载URL 的所有代码移动到回调中:
uploadTask.snapshot.ref.getDownloadURL().then(function (URL) {
//getting the publication time
var dayObj = new Date();
var day = dayObj.getDate();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var month = monthNames[dayObj.getMonth()]
var year = dayObj.getFullYear();
var hour = dayObj.getHours();
var minutes = dayObj.getMinutes();
var seconds = dayObj.getSeconds();
var GlobalUserName = <%=Session["UserId"] %>;
firebase.database().ref('PostUsers/').push({
ImageURL: URL,
userAuthor: GlobalUserName,
day: day,
month: month,
year: year,
hour: hour,
minutes: minutes,
seconds: seconds
});
console.log('User post successfully added to realtime database');
});
这是处理现代Web API时非常常见的模式:它们都是异步的,您的代码必须处理它。
有关详情,请参阅: