许多异步函数应该等待第一个完成

时间:2015-01-21 13:35:29

标签: javascript asynchronous callback wait

考虑以下关于异步函数的设置:

Client.prototype.auth = function(callback) {
    //authenticate the client
    //run callback
};

Client.prototype.get = function() {
    this.auth(function(){
        //run the rest of this `get` function
    }
};
  • 通过eventlistener多次调用get函数,此事件仅触发一次
  • 第一个get应启动身份验证,该身份验证对每个后续调用都有效
  • 验证功能需要几秒钟才能完成
  • 每次后续get调用都不需要重新进行身份验证,因为它仍然有效,因为第一次调用函数
  • 每次后续get调用只应在客户端通过身份验证后运行。如果未经过身份验证,则应等待身份验证完成

重点是阻止10个get来电,以拨打10个auth来电。每当调用第一个auth函数时,其他9个get调用应该等待它完成,然后继续使用get函数的其余部分(在进行身份验证时)

我无法理解这一点。我试图让这个例子尽可能简单

1 个答案:

答案 0 :(得分:1)

我认为你的解决方案是caching。创建一个包含值isUserAutheniticatedisAuthenitcationProcess的缓存,当您需要调用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
        }
    }
};

如果您可以Async.js使用this回答

相关问题