Call An Asynchronous Javascript Function Synchronously

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

    Take a look at JQuery Promises:

    http://api.jquery.com/promise/

    http://api.jquery.com/jQuery.when/

    http://api.jquery.com/deferred.promise/

    Refactor the code:

    
        var dfd = new jQuery.Deferred();
    
    
        function callBack(data) {
           dfd.notify(data);
        }
    
        // do the async call.
        myAsynchronousCall(param1, callBack);
    
        function doSomething(data) {
         // do stuff with data...
        }
    
        $.when(dfd).then(doSomething);
    
    
    

提交回复
热议问题