Call An Asynchronous Javascript Function Synchronously

前端 未结 8 1487
南方客
南方客 2020-11-22 17:37

First, this is a very specific case of doing it the wrong way on-purpose to retrofit an asynchronous call into a very synchronous codebase that is many thousands of lines lo

8条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 17:45

    "don't tell me about how I should just do it "the right way" or whatever"

    OK. but you should really do it the right way... or whatever

    " I need a concrete example of how to make it block ... WITHOUT freezing the UI. If such a thing is possible in JS."

    No, it is impossible to block the running JavaScript without blocking the UI.

    Given the lack of information, it's tough to offer a solution, but one option may be to have the calling function do some polling to check a global variable, then have the callback set data to the global.

    function doSomething() {
    
          // callback sets the received data to a global var
      function callBack(d) {
          window.data = d;
      }
          // start the async
      myAsynchronousCall(param1, callBack);
    
    }
    
      // start the function
    doSomething();
    
      // make sure the global is clear
    window.data = null
    
      // start polling at an interval until the data is found at the global
    var intvl = setInterval(function() {
        if (window.data) { 
            clearInterval(intvl);
            console.log(data);
        }
    }, 100);
    

    All of this assumes that you can modify doSomething(). I don't know if that's in the cards.

    If it can be modified, then I don't know why you wouldn't just pass a callback to doSomething() to be called from the other callback, but I better stop before I get into trouble. ;)


    Oh, what the heck. You gave an example that suggests it can be done correctly, so I'm going to show that solution...

    function doSomething( func ) {
    
      function callBack(d) {
        func( d );
      }
    
      myAsynchronousCall(param1, callBack);
    
    }
    
    doSomething(function(data) {
        console.log(data);
    });
    

    Because your example includes a callback that is passed to the async call, the right way would be to pass a function to doSomething() to be invoked from the callback.

    Of course if that's the only thing the callback is doing, you'd just pass func directly...

    myAsynchronousCall(param1, func);
    

提交回复
热议问题