min*_*eow 7 javascript twitter oauth javascript-events chaining
如果其中一个函数涉及等待弹出窗口,我怎样才能获得一系列连续执行的函数?
在下面的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;
};
}
Run Code Online (Sandbox Code Playgroud)
您的 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");
}
});
Run Code Online (Sandbox Code Playgroud)