1.因为到公司的时候,可能有大数据请求的情况,有时候需要我们同时发送几个请求 而不在乎他们回来的顺序 这个就是并发请求,而有的时候需要我们按照一定的顺序去请求数据 同时数据也要按照我们请求得顺序回来数据 这个就是排队请求
我在桌面上做了俩个按钮一个模拟并发,一个模拟排序请求
下面我们引入axios文件 我不是在vue中测试的 直接使用的是 axios的cdn资源
<script src="https://cdn.bootcss.com/axios/0.19.0/axios.min.js"></script>
2.并发的代码是
function bing(){
//并发请求
axios.all(
[
axios.get('http://127.0.0.1:5050',{params:{type:'a'}}),
axios.get('http://127.0.0.1:5050',{params:{type:'b'}})
]
).then(
axios.spread( (res1,res2) => {
console.log(res1.data,res2.data)
})
)
}
并发回来的情况
排队的代码,排队我用的是axios的post请求
function pai(){
axios.post('http://127.0.0.1:5050',"type=a").then(res=>{
console.log(res.data);
axios.post('http://127.0.0.1:5050',"type=b").then(res=>{
console.log(res.data);
})
})
}
排队回来的情况
插段话: 其实排队 更好的写法 可以 用es7 的 async 和 await 书写 看起来更美观写 更像是同步
async function pai(){
let res1 = await axios.post('http://127.0.0.1:5050',"type=a");
let res2 = await axios.post('http://127.0.0.1:5050',"type=b");
console.log(res1, res2); // 输入结果
}
但好像 axios 的post请求 带参数 不是这样发的哈 想知道 axios.post 怎么发送请求
请移步: axios.post发送请求,axios发送post请求, 携带参数传递给接口_欢迎来到冲哥的前端博客-CSDN博客
3.服务器端的代码 我用 定时器模拟了 大数据回来的的那种延迟状态
var express=require("express");
var bodyParser=require("body-parser");
var cors=require("cors");
var app=new express();
// 创建application/x-www-from-urlencoded
app.use(bodyParser.urlencoded({extended:false}));//解析 x-www-form-urlencoded
//支持ajax跨域请求
app.use(cors({
"Access-Control-Allow-Origin":"*"
}))
app.listen(5050);
app.get("/",(req,res)=>{
//在每一次响应头这里添加ajax跨域请求
res.header("Access-Control-Allow-Origin","*");
var type;
if(req.query.type!=undefined){
type=req.query.type;
}
if(type=="a"){
setTimeout(function(){
res.send({type:"a",count:30})
},3000);
}else if(type=="b"){
setTimeout(function(){
res.send({type:"b",count:40})
},3000);
}else if(type=="c"){
setTimeout(function(){
res.send({type:"c",count:50})
},3000);
}else{
res.send("这次的请求没有带参数!");
}
})
app.post("/",(req,res)=>{
console.log("有人进来了");
res.header("Access-Control-Allow-Origin","*");
console.log(req.body.type);
console.log(11);
var type=req.body.type;
if(type=="a"){
setTimeout(function(){
res.send({type:"你好",count:30})
},3000);
}
if(type=="b"){
setTimeout(function(){
res.send({type:"b",count:40})
},3000);
}
if(type=="c"){
setTimeout(function(){
res.send({type:"c",count:50})
},3000);
}
})
我一年之后 又来 更新下这个博客的内容