axios 与 promise
# axios
axios是基于promise的http库,可以用于浏览器和node.js中
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
# promise 用法文档
http://liubin.org/promises-book/#chapter1-what-is-promise (opens new window)
https://developers.google.com/web/fundamentals/primers/promises?hl=zh-cn (opens new window)
# promise
# 多个请求并列
async tidyData(){
for(let item of itemList){ // itemList存放axios请求
let result = await item;
// TODO 其它事情....
}
}
// 或者
var asyncIterable = {
[Symbol.asyncIterator]() {
return {
i: 0,
next() {
if (this.i < 3) {
return Promise.resolve({ value: this.i++, done: false });
}
return Promise.resolve({ done: true });
}
};
}
};
(async function() {
for await (num of asyncIterable) {
console.log(num);
}
})();
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
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
# N个并发请求
帮助函数处理并发请求。
axios.all(iterable)
axios.spread(callback)
1
2
2
class Scheduler {
constructor(num = 2) {
this.count = 0 // 记录当前正在执行的任务数
this.todoList = [] // 待执行的任务列表
this.num = num // 并发最大数:最多可同时执行的任务个数
}
// 入列
add(promiseCreator) {
if(this.count < this.num) {
this.count ++
promiseCreator().then(() => this.dequeue())
} else {
this.todoList.push(promiseCreator())
}
}
// 出队方法
dequeue() {
this.count --
if(this.todoList.length > 0) {
this.todoList.shift().then(() => this.dequeue())
}
}
}
const timeout = (time) => new Promise(resolve => {
setTimeout(resolve, time)
})
const scheduler = new Scheduler()
const addTask = (time, order) => {
scheduler.add(() => timeout(time).then(() => console.log(order)))
}
addTask(1000, '1')
addTask(500, '2')
addTask(300, '3')
addTask(100, '4')
addTask(400, '5')
addTask(200, '6')
addTask(300, '7')
// 2 3 4 1 6 5 7
// addTask(1000, '1')
// addTask(500, '2')
// addTask(300, '3')
// addTask(400, '4')
// 2314
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
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
# 执行多个并发请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
//注:axios.spread 用于拆分请求结果的。
//promise.all会返回一个数组
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
//两个请求现在都执行完成
}));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# fetch操纵http管道
fetch({
url: 'https://m.douban.com/rexxar/api/v2/movie/电影ID/interests?start=0&count=10&order_by=time'
}).then((res) => {
console.log(res, '开心');
});
1
2
3
4
5
6
2
3
4
5
6
# axios、fetch、ajax(jquery)
axios与fetch是基于promise形式,ajax是callback形式
fetch 脱离了xhr是新语法,默认不传cookie,不能像xhr监听请求进度
上次更新: 2025/04/07, 01:42:58