javascript - Firebase 函数返回
问题描述
我有一个功能来获取图像的链接。当我单击标记以及其他详细信息时,我想显示图像。问题是函数返回未定义。
表结构:
报告文件//表名
-M27OTpU_Be6D8gPQujA //id
1583910088597:“ https://firebasestorage.googleapis.com/v0/b/lto ”
1583910088685:“ https://firebasestorage.googleapis.com/v0/b/lto ”
//this is where i all the function
contentString = '<div class="info-window-content">' +
ret(ids) + '</div>';
//returns the url of the images. I want show it when i click the marker
function ret(ids) {
var pic;
var rootRef = firebase.database().ref().child("Report Files/"
+ ids)
rootRef.once('value').then(function(childs) {
childs.forEach(function (child) {
pic += '<img src="' + child.val() + '" style="display:
block;width:200px;margin-left:auto;margin-right:auto;height="200">';
return pic;
});
});
}
解决方案
尝试以下操作:
function ret(ids) {
return new Promise((resolve, reject) => {
var pic;
var rootRef = firebase.database().ref().child("Report Files/" + ids)
rootRef.once('value').then(function(childs) {
childs.forEach(function (child) {
pic += '<img src="' + child.val() + '" style="display:
block;width:200px;margin-left:auto;margin-right:auto;height="200">';
resolve(pic);
});
});
});
}
promise
从函数中返回 a ret
,resolve(pic)
用于返回完成pic
时的值promise
。然后要获取 的值pic
,您可以执行以下操作:
contentString = '<div class="info-window-content">' +
ret(ids).then((result)=>{result}) + '</div>';
该then()
方法最多接受两个参数:Promise 成功和失败情况的回调函数。
在这里查看更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
推荐阅读
- node.js - 如何在 Express/Node JS 中从服务器端调用 AJAX 函数?
- c# - 如何在 Xamarin.Form 中将 ObservableCollection 排序为字母表
- javascript - 是否可以使用 JavaScript 将 SVG 对象坐标设置为可变变量?
- javascript - 如何在 ajax 回调中获取提供给 ajax 调用的原始数据?
- java - 带有JavaFX组件的Gradle构建jar文件找不到主类
- multithreading - 为什么工人数量与 slurm 批次中指定的数量不匹配?
- c# - 在 ConfigureServices() 中添加两次 AddMvc() 服务是 Asp.Net Core 中的一个好习惯吗?
- wolfram-mathematica - 如何修复“方程可能无法为所有“求解”变量提供解决方案的错误
- python - 尽管使用相同的路径,但终端和 PyCharm 中的 Python 版本不同
- c# - 如何将 Blazor 包含到现有项目中?