Javascript - synchronizing after asynchronous calls

前端 未结 6 1629
北恋
北恋 2021-02-04 02:08

I have a Javascript object that requires 2 calls out to an external server to build its contents and do anything meaningful. The object is built such that instantiating an inst

6条回答
  •  花落未央
    2021-02-04 02:59

    There is barely another way than to have this counter. Another option would be to use an object {} and add a key for every request and remove it if finished. This way you would know immediately which has returned. But the solution stays the same.

    You can change the code a little bit. If it is like in your example that you only need to call another function inside of commonCallback (I called it otherFunction) than you don't need the commonCallback. In order to save the context you did use closures already. Instead of

    foo.bar.sendRequest(new RequestObject, function(resp) {
                me.commonCallback(resp);
                });
    

    you could do it this way

    foo.bar.sendRequest(new RequestObject, function(resp) {
                --me.expectedCallbacks || me.otherFunction(resp);
                });
    

提交回复
热议问题