简体   繁体   English

Javascript 链接等待弹出窗口返回

[英]Javascript chaining to wait for pop up window to return

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.在下面的authBegin函数中,我弹出一个窗口,完成后返回authBegin函数。

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(){
    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;
  };
  
}

Your auth begin method doesn't return anything.您的 auth begin 方法不返回任何内容。 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我喜欢 JS 的一件事是能够指定内联回调,这使它看起来几乎像您正在寻找的链接样式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM