串行发起http请求

如何串行发起http请求

问题:一个数组中有多个url,怎么串行发起这些请求

解决:
方法一:使用promise封装ajax,reduce执行promise数组
client.js

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

var url = [ '/two','/three','/one','four'];
function makePromise(value) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(value);
}, 0)
})
}
let promises = url.map((item, index) => {
return makePromise(item)
});
function Ajax(url) {
return new Promise((resolve, reject) => {
$.ajax({
url: url,
type: "get",
success: function (res) {
console.log(res.title)
resolve()
},
error: function () {
reject();
}

})
})
}
var btn = document.getElementsByTagName('button')[0];
btn.addEventListener('click', function () {
promises.reduce((prev,cur)=>prev.then(()=>cur.then(Ajax)),Promise.resolve())
})

server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var express = require('express');
var app = express();
app.use(express.static('./'))
app.get('/',function (req,res) {
res.sendFile('./index.html')
})
app.get('/one', function (req, res) {
console.log('one ...')
res.send({ code: 200, title: 'one ok' });
});
app.get('/two', function (req, res) {
console.log('two...')
res.send({ code: 200, title: 'two ok' })
})
app.get('/three', function (req, res) {
console.log('three...')
res.send({ code: 200, title: 'three ok' })
})
app.get('/four', function (req, res) {
console.log('four...')
res.send({ code: 200, title: 'four ok' })
})
app.listen(3344);

浏览器控制台打印结果:
client.js:19 two ok
client.js:19 three ok
client.js:19 one ok
client.js:19 four ok

方法二:递归调用
client2.js

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

var url = ['/two', '/three', '/one', 'four'];
function Ajax(url) {
return new Promise((resolve, reject) => {
$.ajax({
url: url,
type: "get",
success: function (res) {
console.log(res.title)
resolve()
},
error: function () {
reject();
}

})
})
}
var req = function (i) {
if (i >=url.length) {
return
}
else {
Ajax(url[i]).then(() => req(i))
i++;
}
}
req(0)

结果同上


tips:
es6箭头函数:未加{}表示直接返回结果,加上{}没有return表示返回undefined;