同步Jquery Ajax调用[重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/6685249/jquery-performing-synchronous-ajax-requests" dir="ltr">jQuery: Performing synchronous AJAX requests</a>
                            <span class="question-originals-answer-count">
                                (4 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2016-07-01 23:19:08Z" class="relativetime">3 years ago</span>.</div>
        </div>
    </aside>

How to ensure that "Test Data" text get displayed in the console only after books details are loaded in vm.books, basically want to perform synchronous ajax call.

Below mention code is not working as expected. any suggestion how to achieve this expected functionality.

$(document).ready(function() {
  var vm = new obj.Books();
  vm.loadBooks();
  console.log("Test Data");
});

var obj = obj || {};
obj.Books = function() {
  var self = this;

  self.books = [];

  self.loadBooks = function() {
    $.ajax({
        url: "somewebapiurl",
        dataType: 'jsonp',
        async: false
      })
      .done(function(data) {
        $.each(data, function(idx, item) {
          self.books.push(item);

        });
      })
      .fail(function(xhr, status, error) {
        alert(status);
      });
  };
};
</div>

How to ensure that "Test Data" text get displayed in the console only after books details are loaded in vm.books, basically want to perform synchronous ajax call.

Just leverage the jQuery Deferred Object's .done function.

self.loadBooks = function() {
  $.ajax({
    url: "somewebapiurl",
    dataType: 'jsonp',
  })
  .done(function(data) {
    $.each(data, function(idx, item) {
      self.books.push(item);

    });
    //do what you want or call the function you want
    console.log("Test Data");
  })
  .fail(function(xhr, status, error) {
    alert(status);
  });
};

@jcubic was right , jsonp does not support synchronous call with async=false.

Therefore,

  • Enabled the CORS in Service side (i.e. somewebapiurl)
  • Set origin details (i.e. origins="http://localhost:19410" headers="*" methods="get" )
  • Removed the datatype='jsonp'
  • Retained async=false

Now it is working as expected.