7

当其中一个函数涉及等待弹出窗口时,如何让一系列函数按顺序执行?

在下面的authBegin函数中,我弹出一个窗口,authBegin完成后返回函数。

但是链接当然不会等待。我怎样才能让它等到窗口回来?

am.authUnlessCurrent().authBegin().collectData();

var authModule=function(){
  
  this.authUnlessCurrent=function(){
    alert("checks auth");
  };

  this.authBegin=function(){
    window.oauth_success = function(userInfo) {
      popupWin.close();
      return this;
    }
    window.oauth_failure = function() {
      popupWin.close();
      return true;
    }
    popupWin = window.open('/auth/twitter');
  };

  this.collectData=function(){
    alert("collect data");
    return this;
  };
  
}
4

1 回答 1

4

您的 auth begin 方法不返回任何内容。如果它不返回任何东西,就没有办法从调用中链接。但是,您真正的问题是您需要等待异步操作(用户在您的弹出窗口上授权某些内容)。因此,您不能链接调用,因为链接调用需要同步(阻塞)流。换句话说,在用户响应之前,没有办法让你的代码阻塞,然后同步收集数据。你必须使用回调。

我喜欢 JS 的一件事是内联指定回调的能力,这使它看起来几乎像您正在寻找的链接样式

这是一个建议,带有您的代码的简化版本:

/**
 * Initialize an authorization request
 * @param {Function} callback method to be called when authentication is complete. 
 *                   Takes one parameter: {object} userInfo indicating success or null 
 *                   if not successful
 */
function authenticate(callback) {
    window.oauth_success = function(userInfo) {
      popupWin.close();
      callback(userInfo);
    }
    window.oauth_failure = function() {
      popupWin.close();
      callback(null);
    }
    var popupWin = window.open('/auth/twitter');
  };    
}

authenticate(function(userInfo){
   if (userInfo) {
     console.log("User succesfully authenticated", userInfo);
   } else {
     console.log("User authentication failed");
   }
});
于 2010-12-06T18:41:43.797 回答