具体来说,它与默认值(async: true)有什么不同?
在什么情况下,我想显式设置async为false,它是否与防止页面上的其他事件发射有关?
具体来说,它与默认值(async: true)有什么不同?
在什么情况下,我想显式设置async为false,它是否与防止页面上的其他事件发射有关?
当前回答
async:false =代码暂停。(等待完成的其他代码。) async:true =代码继续。(没有任何东西被暂停。其他代码没有等待。)
就这么简单。
其他回答
一个用例是在用户关闭窗口或离开页面之前进行ajax调用。这就像在用户可以导航到另一个站点或关闭浏览器之前删除数据库中的一些临时记录。
$(window).unload(
function(){
$.ajax({
url: 'your url',
global: false,
type: 'POST',
data: {},
async: false, //blocks window close
success: function() {}
});
});
Async:False将保留其余代码的执行。一旦你得到ajax的响应,只有这样,其余的代码才会执行。
将async设置为false意味着ajax请求之后的指令必须等待请求完成。下面是必须将async设置为false的一种情况,以便代码正常工作。
var phpData = (function get_php_data() {
var php_data;
$.ajax({
url: "http://somesite/v1/api/get_php_data",
async: false,
//very important: else php_data will be returned even before we get Json from the url
dataType: 'json',
success: function (json) {
php_data = json;
}
});
return php_data;
})();
上面的例子清楚地解释了async:false的用法
通过将其设置为false,我们确保一旦从url中检索到数据,只有在此之后才返回php_data;被称为
async:false =代码暂停。(等待完成的其他代码。) async:true =代码继续。(没有任何东西被暂停。其他代码没有等待。)
就这么简单。
From
https://xhr.spec.whatwg.org/#synchronous-flag
Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs. The future direction is to only allow XMLHttpRequests in worker threads. The message is intended to be a warning to that effect.