Search code examples
javascriptjqueryfirebasepromisedeferred

using plain jquery for firebase anonymous authentication


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.


Solution

  • 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

    1. Create a Promise constructor
    2. If the asynchronous action is to error, mark it with the reject() function.
    3. If the asynchronous action is to succeed, mark it with the resolve() function.
    4. Call the authAnonymously() function and begin the promise chain with the then() function. When successful this function will fire off.
    5. Continue the promise chain with the 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.