felix-cao / Blog

A little progress a day makes you a big success!
31 stars 4 forks source link

现代浏览器的异步请求 Fetch API #191

Open felix-cao opened 3 years ago

felix-cao commented 3 years ago

一、XMLHttpRequest 时代的异步

XMLHttpRequest 时代的异步如果是命令式编程的话:

var url = "https://api.github.com/repos/vuejs/vue-next/commits?per_page=3&sha=";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    console.log(this.responseText);
  }
};
xhttp.open("GET", url, true);
xhttp.send();

二、现代浏览器的Fetch异步

下面的例子可以在 vue3 clone 后,在 dist 中文件夹下的 example 中找到, 也可以去这里看看

const url = 'https://api.github.com/repos/vuejs/vue-next/commits?per_page=10&sha=';
fetch(url)
.then(res => {console.log(response); return response.json()})
.then(data => console.log('data:', data))

上面的代码可以直接在浏览器的Console 中打印出来

image

由此可见,我们可以在浏览器中直接使用 fetch 函数,返回的是一个 Promise 对象。现代浏览器 Chrome, Firefox, Microsoft Edge, Safari 等都已经原生的实现了 fetch API,此外 MDN 中的浏览器支持表显示除IE以外大部分都是支持的 image

Reference

To be Continued