关于Promise的几个基础demo
在node中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15const fs = require('fs');
fs.readFile('14.promise.txt', (err, data) => {
var p = new Promise((resolve, reject) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
p.then((data) => {
console.log(data);
}, (err) => {
console.error(err);
});
});ajax中的应用
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76function ajax(url, fnSucc, fnFail) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.send();
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
fnSucc(xhr.responseText);
} else {
fnFail(xhr.status);
}
}
}
window.onload = function () {
let btn = document.querySelector('button');
let div = document.querySelector('div');
btn.onclick = function () {
var p = new Promise((resolve, reject) => {
ajax('14.promise.txt',
(str) => {
resolve(str);
},
(str) => {
reject(str);
});
});
p.then((str) => {
div.innerHTML = str;
}, (str => {
div.innerHTML = str;
}))
}
}
// 简单的ajax原生实现
var url = 'https://hq.tigerbrokers.com/fundamental/finance_calendar/getType/2017-02-26/2017-06-10';
var result;
var XHR = new XMLHttpRequest();
XHR.open('GET', url, true);
XHR.send();
XHR.onreadystatechange = function() {
if (XHR.readyState == 4 && XHR.status == 200) {
result = XHR.response;
console.log(result);
}
}
var url = 'https://hq.tigerbrokers.com/fundamental/finance_calendar/getType/2017-02-26/2017-06-10';
// 封装一个get请求的方法
function getJSON(url) {
return new Promise(function(resolve, reject) {
var XHR = new XMLHttpRequest();
XHR.open('GET', url, true);
XHR.send();
XHR.onreadystatechange = function() {
if (XHR.readyState == 4) {
if (XHR.status == 200) {
try {
var response = JSON.parse(XHR.responseText);
resolve(response);
} catch (e) {
reject(e);
}
} else {
reject(new Error(XHR.statusText));
}
}
}
})
}
getJSON(url).then(res => console.log(res));一道考察javascript运行机制的面试题
1
2
3
4
5
6
7
8
9
10
11
12
13setTimeout(function() {
console.log(1)
}, 0);
new Promise(function executor(resolve) {
console.log(2);
for( var i=0 ; i<10000 ; i++ ) {
i == 9999 && resolve();
}
console.log(3);
}).then(function() {
console.log(4);
});
console.log(5);执行结果为 2 3 5 4 1
来自Excuse me?这个前端面试在搞事!