How to call an asynchronous JavaScript function and block the original caller

前端 未结 5 983
耶瑟儿~
耶瑟儿~ 2020-12-28 16:57

I have an interesting situation that my usually clever mind hasn\'t been able to come up with a solution for :) Here\'s the situation...

I have a class that has a g

5条回答
  •  無奈伤痛
    2020-12-28 17:16

    spawn a webworker thread to do the async operation for you. pass it info it needs to do the task plus a unique id. the trick is to have it send the result to a webserver when it finishes.

    meanwhile...the function which spawned the webworker sends an ajax request to the same webserver use the synchronous flag of the xmlhttprequest object(yes, it has a synchronous option). since it will block until the http request is complete, you can just have your webserver script poll the database for updates or whatever until the result has been sent to it.

    ugly, i know. but it would block without hogging cpu :D

    basically

    function get(...) {
        spawnWebworker(...);
        var xhr = sendSynchronousXHR(...);
        return xhr.responseTEXT;
    }
    

提交回复
热议问题