首页 > 解决方案 > 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;
    });
    });
      }

标签: javascriptfirebasefirebase-realtime-database

解决方案


尝试以下操作:

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 retresolve(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


推荐阅读