Call An Asynchronous Javascript Function Synchronously

前端 未结 8 1492
南方客
南方客 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:49

    The idea that you hope to achieve can be made possible if you tweak the requirement a little bit

    The below code is possible if your runtime supports the ES6 specification.

    More about async functions

    async function myAsynchronousCall(param1) {
        // logic for myAsynchronous call
        return d;
    }
    
    function doSomething() {
    
      var data = await myAsynchronousCall(param1); //'blocks' here until the async call is finished
      return data;
    }
    

提交回复
热议问题