我有这个代码(ajax 是异步的):
function echoHello()
{
return "hello";
}
function echoWorld()
{
return $.ajax({
//this will return "world";
});
}
console.log(echoHello());
$.when(echoWorld()).done(function(response)
{
console.log(response);
});
输出“hello”和“world”(按顺序)。但如果稍微改变一下,那么 console.log()
的顺序就会不同:
function echoHello()
{
return "hello";
}
function echoWorld()
{
return $.ajax({
//this will return "world";
});
}
$.when(echoWorld()).done(function(response)
{
console.log(response);
});
console.log(echoHello());
是否保证相同的输出?或者它可能会输出“world”,然后输出“hello”?
最佳答案
$.ajax() 返回 jqXHR实现 Promise 接口(interface)的对象。如果async选项为 false,它会发送同步 Ajax 请求并返回已解决 Promise。
对于$.when()如果参数既不是 Deferred 也不是 Promise 也不是 Thenable,则它返回一个已解决 Promise。
因此下面的示例将打印“Sync”、“Hello”、“World”、“Async”。
jQuery(document).ready(function( $ ){
let echoHello = () => "Hello";
let echoAsync = () => $.ajax({url: "data:text,Async"});
let echoSync = () => $.ajax({ async: false, url: "data:text,Sync" });
let log = response => console.log(response);
$.when(echoAsync()).done(log); // logs "Async"
$.when(echoSync()).done(log); // logs "Sync"
$.when(echoHello()).done(log); // logs "Hello"
console.log('World'); // logs "World"
});
并且,供您引用,从 jQuery 1.8 开始,不推荐使用 async: false 与 jqXHR。
关于javascript - jQuery 的 AJAX 的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63025405/