开发者

Javascript chaining to wait for pop up window to return

开发者 https://www.devze.com 2023-01-29 07:22 出处:网络
How can I get a chain of functions to execute sequentially, when one of it involves waiting for a popup window?

How can I get a chain of functions to execute sequentially, when one of it involves waiting for a popup window?

In the authBegin function below, I am popping up a window, which returns to the authBegin function when completed.

But the chaining is of course not waiting for that. How can I make it wait till the window comes back?

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

var authModule=function(){
  
  this.authUnlessCurrent=function(){
    ale开发者_StackOverflow中文版rt("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;
  };
  
}


Your auth begin method doesn't return anything. There's no way to chain from a call if it doesn't return anything. However, your real problem is the fact that you need to wait on an asynchronous action (the user to authorize something on your popup). Therefore, you can't chain the calls, since chained calls require a synchronous (blocking) flow. In other words, there is no way to make your code block until the user responds, then collect data synchronously. You have to use callbacks.

One of the things I love about JS is the ability to specify callbacks inline, which makes it almost look like the chaining style you're looking for

Here's a suggestion, with a simplified version of your code:

/**
 * 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");
   }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消