Reputation: 3083
Peep is always returned from the function as undefined. Can someone point me to the problem? In the success function the snapshot is returned as expected. I think it's a scoping issue.
function getPerson( id ) {
var ref = new Firebase( "https://foo.firebaseio.com/people/" + id ),
peep;
// Attach an asynchronous callback to read the data at our people reference
ref.once( "value", function( snapshot ) {
//success
peep = snapshot;
}, function ( errorObject ) {
//error
//console.log( "The read failed: " + errorObject.code );
});
return peep;
}
Upvotes: 0
Views: 2447
Reputation: 538
The once()
method is asynchronous which is why a callback is used. You are returning peep
before it even has a value. You need to return peep
after it is defined in the callback.
function getPerson( id ) {
var ref = new Firebase( "https://foo.firebaseio.com/people/" + id ),
peep;
// Attach an asynchronous callback to read the data at our people reference
return ref.once( "value", function( snapshot ) {
//success
peep = snapshot;
return peep;
}, function ( errorObject ) {
//error
//console.log( "The read failed: " + errorObject.code );
});
}
And then use it like this:
getPerson('9234342').then(function(snapshot) {
console.log(snapshot.val());
}).catch(function(error) {
console.error(error);
});
Upvotes: 1
Reputation: 2753
The once() method is asynchronous that is why callback is used. You can pass a callback as a parameter to the getPerson function
alongside the id.
function getPerson(id, callback) {
var ref = new Firebase( "https://foo.firebaseio.com/people/" + id );
ref.once( "value", function(snapshot) {
var peep = snapshot;
// error will be null, and peep will contain the snapshot
callback(null, peep);
}, function (error) {
// error wil be an Object
callback(error)
});
}
getperson('9234342', function (err, result) {
console.log(result);
});
Upvotes: 5
Reputation: 3783
Yes it should be because the success callback is not fired immediately. It receives data then get into it.
Try returning the peep
inside the callback like.
return ref.once( "value", function( snapshot ) {
//success
peep = snapshot;
return peep;
}, function ( errorObject ) {
//error
//console.log( "The read failed: " + errorObject.code );
});
Hope it helps.
Upvotes: 2