Pattern for wrapping an Asynchronous JavaScript function to make it synchronous

前端 未结 7 1457
迷失自我
迷失自我 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 04:50

    You can try something like:

    function synch()
    {
        var done = false;
        var returnVal = undefined;
    
        // asynch takes a callback method
        // that is called when done
        asynch(function(data) {
            returnVal = data;
            done = true;
        });
    
        while (done == false) {};
        return returnVal;
    }
    

    But that may freeze your browser for the duration of the asynch method...

    Or take a look at Narrative JavaScript: Narrative JavaScript is a small extension to the JavaScript language that enables blocking capabilities for asynchronous event callbacks. This makes asynchronous code refreshingly readable and comprehensible.

    http://neilmix.com/narrativejs/doc/index.html

    Mike

提交回复
热议问题