如何将Firebase中的snapshot.val()返回到变量? [英] How do I return a snapshot.val() from Firebase to a variable?

查看:31
本文介绍了如何将Firebase中的snapshot.val()返回到变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var getListings = function () {
    listingsRef.once("value").then(function(snapshot) {
        console.log(snapshot.val());
    }, function (errorObject) {
        console.log("The read failed: " + errorObject.code);
    });
};

我有以下方法. console.log(snapshot.val())正常运行.但是,如果我 return snapshot.val()它返回未定义.我似乎无法弄清楚该怎么做 var currentSnapshot = getListings()

I have the following method. console.log(snapshot.val()) is working as expected. However, if I return snapshot.val() it returns undefined. I cannot seem to figure out how to do var currentSnapshot = getListings()

推荐答案

返回从列表中获得承诺.使用解决和拒绝功能来消耗Promise.

Return a Promise from get listing. Consume the Promise using resolve and reject functions.

var getListings = function () {
    return listingsRef.once("value");
};


var currentSnapshot;

function loadListing(){
    getListings().then(setListing, showError);
}

function setListing(snapshot){
    currentSnapshot = snapshot.val()
}

function showError(e){
    console.log(e);
}

function init(){
    loadListing();
}


另一种解决方案是使用回调的较旧方法.不建议这样做,因为如果有多个嵌套的异步调用,它可能导致代码难以管理.承诺是对由回调创建的混乱的解决方案.


The other solution is the older way of using callbacks. This is not recommended as it can lead to unmanageable code if there are multiple nested async calls. Promises are a solution to the mess created by callbacks.

var currentSnapshot;
function getListings() {
    listingsRef.once("value", setListing, showError);
};

function setListing(snapshot){
    currentSnapshot = snapshot.val()
}

function showError(e){
    console.log(e);
}

function init(){
    getListings();
}

这篇关于如何将Firebase中的snapshot.val()返回到变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆