简体   繁体   中英

Promise deferred ajax api jQuery

I don't understand promises/deferred very much... I have something like that :

function callAjax() {
  return $.ajax({ 
     type: 'post',
     dataType: 'jsonp',
     data: {status: status, name: name},
     url: '/test',
     xhrFields: {
         withCredentials: true
     }
  });
} 

function connectAjax() {
  var msg = 'doesnt work';
  var promise = callAjax();

  promise.then(function(data, textStatus, xhr) {
    msg = 'it worked !';
  }, function(data, textStatus, xhr) {
    msg = 'it failed !';
  });

  console.log(msg); // output 'doesnt work'
}

I have tried a lot of different things (always, done, etc..) but couldn't make it work.

I use jsonp but my request isn't cross domain. I expect a 500 error from the server for my request.

For your example to work, you have to put the 'console.log(...)' statment INSIDE the two callback functions you register on the promise with .then(.., ..).

You have to keep in mind that the promise callback functions get called, only when the ajax call is finished. Your script however does not wait until this happens and 'console.log(msg);' is executed before the ajax call returns.

This is a great example for the non-blocking nature of JavaScript.

For more detailed understanding look up resources on the JS event loop: https://thomashunter.name/blog/the-javascript-event-loop-presentation/ Understanding the Event Loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM