使用普通 jquery 进行 firebase 匿名身份验证

using plain jquery for firebase anonymous authentication

我正在尝试理解 deferred 和 promise。在理解核心概念之前,我不想使用任何库 angularfire 等。这就是我正在尝试做的事情,但总是得到错误的状态。请指教。 .........

 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(); 
   ........

请忽略任何语法错误。早些时候,我将 fbref.authAnonymously 调用包装在一个单独的函数中。在调试模式下它会失败,但在 运行 模式下它总是会成功。 我确定我的 firebase 实例未启用匿名身份验证。

已编辑:标题拼写错误。

Promise 现在是 JavaScript 的正式部分,您可以在最新的浏览器中使用它们而无需库。

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

下面是这个例子中的五个步骤

  1. 创建一个 Promise 构造器
  2. 如果异步操作出错,用reject()函数标记。
  3. 如果异步动作要成功,用resolve()函数标记。
  4. 调用 authAnonymously() 函数并使用 then() 函数开始承诺链。成功后,此功能将触发。
  5. 使用 error() 函数继续承诺链。如果发生错误,catch() 函数不会触发,但此 error() 函数会触发。

Promises 对于一次性回调 很有效。对于 Firebase,这非常适合身份验证方法和 once() 调用。这对于重复回调来说不是很好,比如 on() 函数。