如何正确运行firebase功能?

时间:2019-01-06 10:50:29

标签: javascript firebase firebase-realtime-database

此函数将返回initiate_session, initiate_session[user_session].events, user_session的值 在运行Firebase函数之前。

如何首先运行firebase函数??

function createSession() {
var user_session = randomCharacters(20) //8iKhA4Aq2!6gZ)890ip@;
var ip = '127.0.0.1';
var initiate_session = new Object();
var session_started = new Date().getTime();


firebase.database().ref(user_session).once('value', function (snapshot) {
    if (snapshot.exists()) {
        console.log('session exists');
        createSession();
    } else {
        console.log('session not exists')

        initiate_session[user_session] = {
            ip: ip,
            session_started: session_started,
            events: {}
        };

        firebase.database().ref(user_session).set({
            ip: ip,
            session_started: session_started,
            events: {}
        });
    }
});

console.log('new session', initiate_session);
return [initiate_session, initiate_session[user_session].events, user_session];}

1 个答案:

答案 0 :(得分:2)

这是因为Firebase函数是异步的-获取快照的方法中的代码是回调,该调用在Firebase读取完成后执行,这可能需要几秒钟。但是,一旦您通过.once(...)分派了读取请求,您的执行流程就会继续并调用返回。

有几种可能的解决方案:

  1. 将回调参数传递给您的createSession()方法,该方法将使用您尝试返回的值进行调用,而不是直接返回它们。

  2. 从您的方法中返回一个承诺,该承诺会解析为您提供要返回的值。

  3. 对Firebase调用使用async / await语法。此问题已涵盖此问题:running queries in firebase using async / await

#1的大致示例

function createSession(onSessionCreated) {
    var user_session = "whatever";
    var initiate_session = new Object();

    firebase.database().ref(user_session).once('value', function (snapshot) {
        // do things with the snapshot
        onSessionCreated(initiate_session, initiate_session[user_session].events, user_session)
    });
}

// usage:
createSession(function (initiate_session, events, user_session) {
    // do things with initiate_session, events and user_session
});

#2的示例

function createSession() {
    var user_session = "whatever";
    var initiate_session = new Object();

    firebase.database().ref(user_session).once('value').then(function (snapshot) {
        // do things with the snapshot
        return [initiate_session, initiate_session[user_session].events, user_session];
    });
}

// usage:
createSession().then(function (results) {
    // do things with results (i.e. the three elements in the array above)
});

3的示例

async function createSession() {
    var user_session = "whatever";
    var initiate_session = new Object();

    const snapshot = await firebase.database().ref(user_session).once('value');
    // do things with the snapshot

    return [initiate_session, initiate_session[user_session].events, user_session];
}

// usage:
const results = await createSession();

如果您是async / await代码的新手,它可能不是最容易开始的地方,因为它可能需要在代码的其他位置进行更改,但是this article是如果您热衷于学习,那就是很好的资源。