1 function getData(url, type, data){ // 这个相当于请求的数据
2 return new Promise((resolve, reject) => {
3 let xhr = new XMLHttpRequest();
4 xhr.open('get', url);
5 xhr.send();
6 xhr.onreadystatechange = function(){
7 if(xhr.readyState !== 4){
8 return;
9 }
10 if(xhr.status == 200){
11 resolve(xhr.responseText)
12 }else{
13 reject('失败')
14 }
15 }
16 })
17 }
18
19 // async 函数返回的是一个Promise 实例对象,可以通过then ()链式调用; async 函数 通过 return 语句传递数据 ,通过 then() 接收数据
20 async function ajax(url){
21 // 正常情况下,await命令后面是一个 Promise 对象,返回该对象的结果。如果不是 Promise 对象,就直接返回对应的值。
22 let result = await getData(url);
23 // console.log(result);
24
25 // await 返回的结果就是数据
26 // let result = await 'hello world';
27
28 // return 传递的数据会自动被then() 里边的回调函数接收
29 return result
30 }
31
32 // let res = ajax('http://localhost:3000/posts')
33 // console.log(res);
34 ajax('http://localhost:3000/posts').then(result => {
35 console.log(result);
36 })