Pattern for wrapping an Asynchronous JavaScript function to make it synchronous

前端 未结 7 1446
迷失自我
迷失自我 2020-12-09 04:33

I\'m working with a JavaScript API where most of the functions are asynchronous. The API is the WebKit JavaScript Database API which is a binding to a subset of functionali

相关标签:
7条回答
  • 2020-12-09 05:09

    We are using GWT RPC which also has an async API. The solution that we are currently using to make several async calls in serial is call chaining:

    callA(function(resultA) {
        callB(resultA, function(resultB) {
            callC(); //etc.
        });
    });
    

    This nested approach achieves what you want but it is verbose and hard to read for newcomers. One of the approaches that we have investigated is adding the calls that we need to make to a stack and executing them in order:

    callStack = [
        callA(),
        callB(),
        callC()
    ];
    
    callStack.execute();
    

    Then the callstack would manage:

    1. Invoking the calls in serial (i.e. the wiring in the first example)
    2. Passing the result from one call forward to the next.

    However, because Java doesn't have function references, each call on the call stack would require an anonymous class so we stopped short of such a solution. However, you may have more success in javascript.

    Good luck!

    0 讨论(0)
提交回复
热议问题