简体   繁体   中英

Setting timeout on .once in Firebase

I use Firebase's .once method to get one-off values from the database - ie get name of a user.

userRef.once('value', function (data) {
    console.log('gots it')
    deferred.resolve(data.val());
}, function(error) {
    console.log('error, maybe it timed out');
    deferred.reject(error);
});

I want to be able to cancel this 'request' after a certain period of time, for example if the network is poor, and then call the error callback.

Is this possible?

I realise this isn't an answer to the OP's question, which is a year old in any case. But I just had the same problem (but using the ionic framework). So in case it's useful for anyone, here's what I came up with.

var timeoutOnce = function(ref, eventType) {
    var deferred = $q.defer();
    $timeout(function() {
        deferred.reject("TIMEOUT");
    }, TIMEOUT_PERIOD)
    ref.once(eventType, 
        function(data) {
            deferred.resolve(data);
        }, 
        function(error) {
            deferred.reject(error);
        }
    );
    return deferred.promise;
}

And so this call:

ref.once('value', success, failure);

becomes:

timeoutOnce(ref, 'value').then(success, failure);

Seems to work for me. Obviously set TIMEOUT_PERIOD to whatever you want.

For the time being I am hacking this in the fashion:

        var hasTimedOut = false,
            timeout;

        timeout = $window.setTimeout(function() {
            hasTimedOut = true;
            deferred.reject({
                timedOut: true
            });
        }, 10000);

        userRef.once('value', function (data) {
            if (!hasTimedOut) {
                clearTimeout(timeout);
                deferred.resolve(data.val());
            }
        }, deferred.reject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM