Javascript 链接等待弹出窗口返回
当其中一个函数涉及等待弹出窗口时,如何让一系列函数按顺序执行?
在下面的 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;
};
}
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(){
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;
};
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 auth begin 方法不会返回任何内容。如果调用不返回任何内容,则无法链接该调用。然而,您真正的问题是您需要等待异步操作(用户在弹出窗口上授权某些内容)。因此,您无法链接调用,因为链接调用需要同步(阻塞)流。换句话说,没有办法让你的代码阻塞直到用户响应,然后同步收集数据。你必须使用回调。
我喜欢 JS 的原因之一是能够内联指定回调,这使得它几乎看起来像您正在寻找的链接样式
这是一个建议,其中包含代码的简化版本:
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: