当一个页面有异步请求又有同步请求,页面是如何执行。例如,页面有3个同步请求,3个异步请求,是先显示什么,再显示什么?
下面代码里面有4个同步,2个异步,后端设置了2秒后返回数据。
window.onload = function(){
ajax(‘http://127.0.0.1:8080/getasync‘,‘get‘,false,function(res){
console.log(‘我是同步1‘+res)
})
ajax(‘http://127.0.0.1:8080/getasync‘,‘get‘,false,function(res){
console.log(‘我是同步2‘+res)
})
ajax(‘http://127.0.0.1:8080/getasync‘,‘get‘,false,function(res){
console.log(‘我是同步3‘+res)
})
ajax(‘http://127.0.0.1:8080/getasync‘,‘get‘,false,function(res){
console.log(‘我是同步4‘+res)
})
console.log(‘我是同步后显示‘)
ajax(‘http://127.0.0.1:8080/getasync‘,‘get‘,true,function(res){
console.log(‘我是异步1‘+res)
})
ajax(‘http://127.0.0.1:8080/getasync‘,‘get‘,true,function(res){
console.log(‘我是异步2‘+res)
})
console.log(‘我是最后显示‘)
}
function ajax(url,type,async,callback){
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status == 200){
callback(xhr.responseText)
}
}
xhr.open(type,url,async)
xhr.send(null)
}
页面会先执行同步,再执行
同步:
单线程,相当于排队,当前发出请求后,浏览器什么都不能做,必须得等到请求完成返回数据之后,才会执行后续的代码。
客户端请求(等待)->服务端处理->响应->页面载入
异步:
页面上的操作和服务器端的操作互相之间不会造成阻塞,例如:检查用户名是否重复。

ps:第一次写博客
原文:https://www.cnblogs.com/sosohui/p/10234840.html