Reputation: 1096
Can someone please explain how to use promises with Firebase with my code below:
var p = new Promise(function(resolve, reject) {
var data=null;
var ref = db.ref("/");
ref.once("value", function(snapshot) {
data = snapshot.val();
});
data.onload = function() {
console.log(data+" onload");
if (data!=null) {
resolve('Success!');
}
else {
reject('Failure!');
console.log('failed');
}
}
});
p.then(function() {
/* do something with the result */
console.log(data+" done");
}).catch(function() {
/* error :( */
console.log("error");
});
I'm wanting to wait until I 'hear back' from data = snapshot.val();
before I call my next function. What is the correct way to go about this? I'm clearly not understanding promises. I'm trying to follow this tutorial.
Upvotes: 1
Views: 1837
Reputation: 505
Promises are built into firebase directly.
var ref = firebase.database().ref();
ref.once('value')
.then(function (result) {
// This only happens after the data has been returned
console.log(result.val());
})
.catch(function (err) {
// This is where errors land
console.log('Error', err.code);
});
Version 3 of firebase has you covered so you do not need to create container promises. :)
Upvotes: 2