考虑以下关于异步函数的设置:
Client.prototype.auth = function(callback) {
//authenticate the client
//run callback
};
Client.prototype.get = function() {
this.auth(function(){
//run the rest of this `get` function
}
};
get
函数通过事件监听器被多次调用,并且该事件仅触发一次- 第一个
get
应该启动身份验证,该身份验证对于后续的每个调用都保持有效 - 身份验证功能需要几秒钟才能完成
- 随后的每个
get
调用都不需要重新进行身份验证,因为由于第一个函数调用,它仍然有效 - 每个后续的
get
调用只能在客户端经过身份验证后运行。如果未通过身份验证,则应等待身份验证完成
重点是防止 10 个 get
调用引发 10 个 auth
调用。每当调用第一个 auth
函数时,其他 9 个 get
调用都应该等待它完成,然后继续执行其余的 get
功能(正在验证时)
我无法理解这个问题。我试图让这个例子尽可能简单
最佳答案
我认为您的解决方案是 caching 。创建一个保存值 isUserAuthenitated
和 isAuthenitcationProcess
的缓存,当您需要调用 auth
时,只需检查用户是否已通过身份验证,如果没有则调用它。在auth
订阅回调中,检查身份验证过程是否打开,如果没有,则进行身份验证设置并调用所有已注册的回调。 Globallist 不是最干净的实现选项 Observable pattern所以你可以做到 in other way
这是我的想法:
var isAuthenticated = false;
var isAuthenticatioProcess = false;
var authenticationCallbacks = [];
Client.prototype.auth = function(callback) {
authenitcationCallbacks.push(callback);
if (isAuthenticonProcess) {
return;
}
//authenticate
authenitcationCallbacks.forEach(function(call) {
call();
});
authenitcationCallbacks = [];
isAuthenticonProcess = false;
isAuthenticated = true;
};
Client.prototype.get = function() {
if (isAuthenticated) {
this.auth(function(){
//run the rest of this `get` function
}
} else {
function(){
//run the rest of this `get` function
}
}
};
关于javascript - 许多异步函数应该等待第一个函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28068595/