有些高级方法,掌握了原生的写法,可以帮助我们更好的使用它。或者在不支持的情况下可以自己去实现一个。

实现一个异步请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<input type="button" value="按钮" id="btn" />
<script>
window.onload = function() {
let btn = document.getElementById('btn');
btn.onclick = function() {
// 1.创建对象
let xhr = new XMLHttpRequest();
console.log('xhr对象创建完', xhr.readyState) // 0

// 2.连接:true异步,false同步
xhr.open('GET', 'data/1.txt', true)
console.log('已连接服务器', xhr.readyState) // 1

// 3.发送
xhr.send();

// 4.接受:当通信状态改变
xhr.onreadystatechange = function() {
if (xhr.readyState == 2) {
console.log('send完', xhr.readyState)
} else if (xhr.readyState == 3) {
console.log('头接收完', xhr.readyState)
} else if (xhr.readyState == 4) {
console.log('body接收完,但是能否成功返回内容尚未可知,需要判断状态码', xhr.readyState)
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
console.log('成功', xhr.status);
console.log(xhr);

let json = null;
try {
json = JSON.parse(xhr.responseText);
} catch (e) {
json = eval('(' + xhr.responseText + ')');
}
console.log(json);
// 读取data/2.xml
// console.log(xhr.responseXML);
// let p = xhr.responseXML.getElementsByTagName('person')[0];
// console.log(p.children);
} else {
console.log('失败', xhr.status);
}
}
}
}
}
</script>

实现一个Promise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Promise2 {
constructor(fn) {
const _this = this;
// 重点
this.__queue = [];

this.__succ_res = null;
this.__erro_res = null;
this.status = '';

fn(function(...arg) {
_this.__succ_res = arg;
_this.status = 'succ';

_this.__queue.forEach(json => {
json.fn1(...arg);
})
}, function(...arg) {
_this.__erro_res = arg;
_this.status = 'error';

_this.__queue.forEach(json => {
json.fn2(...arg);
})
});
}

then(fn1, fn2) {
if (this.status == 'succ') {
fn1(...this.__succ_res);
} else if (this.status == 'error') {
fn2(...this.__erro_res);
} else {
this.__queue.push({ fn1, fn2 })
}
}
}

Promise2.all = function(arr) {
let result = [];

return new Promise2((resolve, reject) => {
let i = 0;
let next = function() {
arr[i].then(function(res) {
result.push(res);

i++;
if (i == arr.length) {
resolve(result)
} else {
next();
}
}, function(res) {
reject(res)
})
}
next();
})
}

调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let p = new Promise2((resolve, reject)=>{
setTimeout(function(){
resolve(15);
}, 1000)
});
p.then((res)=>{
console.log(res)
}, (res)=>{
alert('失败')
})

Promise2.all([
$.ajax({ url: 'data/1.txt', dataType: 'json' }),
$.ajax({ url: 'data/2.txt', dataType: 'json' })
]).then((arr) => {
console.log(arr);
}, (arr) => {
alert('失败')
})