I am trying to understand deferred and promise. I dont want to use any library angularfire etc., before understanding the core concept. This is what i am trying to do and always getting a wrong status. Please advise. ........
var defObj = $.Deferred();
var fbref = new Firebase(<<firebase url>>);
defObj.done(function() {
console.log('Success')
}
);
defObj.fail(function() {
console.log('Fail')
}
);
defObj.resolve(
fbref.authAnonymously(function(error, authData) {
if (error) {
defObj.reject();
}
/*
else if (authData) {
defObj.resolve();
}
*/
});
return defObj.promise();
........
Pls ignore any syntax errors. Earlier I wrapped the fbref.authAnonymously call in a seperate function. In debug mode it was falling to fail but in run mode it was always going to success. I am sure my firebase instance is not enabled for anonymous authentication.
edited : misspelt title.
Promises are now an official part of JavaScript and you can use them in the latest browsers without a library.
function authAnonymously() {
// 1
var promise = new Promise(
function(resolve, reject) {
var ref = new Firebase(<<firebase url>>);
ref.authAnonymously(function(error, authData) {
if (error) {
reject(error); // 2
} else {
resolve(authData); // 3
}
});
});
}
authAnonymously()
.then((authData) => console.log(authData)) // 4
.catch((error) => console.error(error)); // 5
Here are the five steps in this example
reject()
function. resolve()
function.authAnonymously()
function and begin the promise chain with the then()
function. When successful this function will fire off.error()
function. If the error occurs, the catch()
function won't fire, but this error()
function will.Promises work well for one time callbacks. For Firebase, this is great for authentication methods and once()
calls. This is not great though for repeated callbacks, like the on()
function.