Waiting for API call to finish in Javascript before continuing

后端 未结 3 1250
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条回答
  •  自闭症患者
    2020-12-30 11:16

    The question that is asked 100 times a day and seems impossible to have one answer.

    The call is asynchronous so it is impossible to do it in one step. Basic example of what you expect.

    function one() {
      var a = 1;
      return a;
    }
    alert( one() );
    

    What is actually happening:

    function one() {
      var a;
      window.setTimeout( 
         function() {
            a = 1;
         }, 2000);
      return a;  //This line does not wait for the asynchronous call [setTimeout/ajax call] to run. It just goes!
    }
    alert( one() );
    

    What you need to do is break it up into two parts.

    function one( callback ) {   
       window.setTimeout( function(){  //acting like this is an Ajax call
            var a = 1;
            callback(a);
       },2000);
    }
    function two( response ) {
       alert(response);
    }
    one( two );
    

    So in your case you would need to break up your code to handle it in two chunks.

    function makeCall( callback ) {
        var body = 'Test post';
          FB.api('/me/feed', 'post', { message: body }, function (response) {
            if (!response || response.error) {
             var finalresponse = response.error;
            } else {
              finalresponse = 'Post ID: ' + response.id;
            }
            callback(finalresponse);
          });
    }
    
    
    function processResponse( response ) {
        console.log(response);
    }
    makeCall(processResponse);
    

提交回复
热议问题