Skip to content

你真的了解XMLHttpRequest.open(method, url, async)中async么? #19

@jiefancis

Description

@jiefancis

web前端想要使用原生js创建一个http请求,可以选择的方式有:sendBeacon(url, data)、XMLHttpRequest、fetch、WebSocket等,但是我们了解的最多的
还是XMLHttpRequest这个api,通过XMLHttpRequest创建一个http请求需要经过这几个步骤:

  • 创建一个xhr对象
  • 初始化请求(建立连接)
  • 监听请求的状态变化
  • 发送请求数据

在初始化请求时,文档中写到:同步请求,send()方法直到收到答复前不会返回。异步请求,send()方法请求后会立即返回;open(method, url, async)中的async的值true / false对程序的执行会产生什么影响呢?看下面的代码

  • 异步
var xhr = new XMLHttpRequest()
xhr.open('get', 'https://www.baidu.com',true)
xhr.onreadystatechange = function(){
    console.log('onreadystatechange', xhr.readyState)
}
xhr.send()
console.log('end', xhr.readyState)

(在百度页面控制台中)执行结果为:
end 1
onreadystatechange 2
onreadystatechange 3
onreadystatechange 4

  • 同步
var xhr = new XMLHttpRequest()
xhr.open('get', 'https://www.baidu.com',false)
xhr.onreadystatechange = function(){
    console.log('onreadystatechange', xhr.readyState)
}
xhr.send()

console.log('end', xhr.readyState)

(在百度页面控制台中)执行结果为:
onreadystatechange 4
end 4
 
var xhr = new XMLHttpRequest()
xhr.open('get', 'https://www.baidu.com',false)
xhr.onreadystatechange = function(){
    console.log('onreadystatechange', xhr.readyState)
}
console.log('end', xhr.readyState)
xhr.send()


(在百度页面控制台中)执行结果为:
end 4
onreadystatechange 4
 

通过同步的例子,发现同步请求,send方法后的逻辑将会阻塞,收到答复后程序才会继续往下执行;主线程上的同步请求很容易破坏用户体验

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions