我不太理解许诺/延期...我有类似的东西:
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'
}我尝试了很多不同的东西(总是,完成,等等)但不能让它工作。
我使用jsonp,但我的请求不是跨域的。对于我的请求,我期望从服务器得到一个500错误。
发布于 2014-10-27 21:43:16
为了让你的例子起作用,你必须把'console.log(...)‘使用.then(..,..)在promise上注册的两个回调函数中的语句。
您必须记住,只有当ajax调用完成时,才会调用promise回调函数。但是,在ajax调用返回之前,您的脚本不会等到发生这种情况并执行'console.log(msg);‘。
这是一个很好的例子,说明了JavaScript的非阻塞特性。
有关更详细的理解,请参阅JS事件循环上的参考资料:https://thomashunter.name/blog/the-javascript-event-loop-presentation/ Understanding the Event Loop
https://stackoverflow.com/questions/26588702
复制相似问题