Reputation: 697
I use Firebase's .once method to get one-off values from the database - i.e. 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?
Upvotes: 2
Views: 2025
Reputation: 652
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.
Upvotes: 3
Reputation: 697
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);
Upvotes: 2