Javascript to wait for popup to appear

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

In the authBegin function below, I display a window that returns to the authBegin function when completed.

But the chain, of course, does not expect this. How can I make him wait until the window returns?

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; }; } 
+7
javascript javascript-events chaining oauth twitter
source share
1 answer

Your start method does not return anything. There is no way to contact the call if it does not return anything. However, your real problem is that you need to wait for the asynchronous action (the user must authorize something in the pop-up window). Thus, you cannot forward calls because call chains require a synchronous (blocking) flow. In other words, there is no way to make your code block until the user answers, and then collect the data synchronously. You must use callbacks.

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

Here is 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"); } }); 
+4
source share

All Articles