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

Numerous asynchronous functions should wait for completion of first

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

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

Client.prototype.get = function() {
    this.auth(function(){
        //run the rest of this `get` function
    }
};

要点是防止 10 get 调用触发 10 auth 调用。每当第一个 auth 函数被调用时,其他 9 个 get 调用应该等待它完成,然后继续 get 函数的其余部分(同时被验证)

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

我认为适合您的解决方案是 caching. Make a cache that will hold value isUserAutheniticated and isAuthenitcationProcess and when you need to call auth just check if user is authenticated and if not call it. Inside auth subscribe callback, check if authentication process is open if not do authentication set and call all registered callbacks. Globallist is not cleanest option to implement Observable pattern so you can do it 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 look at this 回答