Waiting for API call to finish in Javascript before continuing

后端 未结 3 1253
Happy的楠姐
Happy的楠姐 2020-12-30 10:46

something I\'ve struggled with in the past and am struggling with today is preventing an API/AJAX from continuing until you\'ve recieved your response. currently I\'m workin

3条回答
  •  梦毁少年i
    2020-12-30 11:11

    In JavaScript, there is no concept of waiting or yielding. JavaScript continues execution, without interruption, of your code to its end. It seems weird and troublesome at first, but it has its advantages.

    So the idea in scenarios such as this is that the code you wish to execute after receiving your response should be put into the callback that you give to FB.api(). You'll have to break out the code after your return statement into the response callback so that it can be executed when the response is received.

    This is what you might expect from JavaScript if it were like most languages (such as C++/Java):

    var futureResult = SomeAsyncCall();
    futureResult.Wait(); //wait untill SomeAsyncCall has returned
    var data = futureResult.GetData();
    //now do stuff with data
    

    The idea in JavaScript, however, is based around callbacks when dealing with asynchrony:

    SomeAsyncCall(function(result) {
        var data = result.GetData();
        //now do stuff with data
    });
    

提交回复
热议问题