async\await是配合promise使用的,async/await是ES7引入的新语法,可以更加方便的进行异步操作
- async关键字用于函数上(async函数的返回值是promise的实例对象)
- await关键字用于async函数当中(await可以得到异步的结果)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!--
axios 是属于异步处理的
async/await的基本用法
是ES7引入的新语法,可以更加方便的进行异步操作
async关键字用于函数上(async函数的返回值是promise的实例对象)
await关键字用于async函数当中(await可以得到异步的结果)
-->
<!--
处理多个异步请求
-->
<script src="./axios/axios.js"></script>
<script>
async function queryData(){
var ret = await axios.get('http://localhost:3000/data');
console.log(ret);
return ret.data;
};
// async function queryData(){
// var ret = await new Promise(function(resolve,reject){
// setTimeout(function(){
// resolve('nihao');
// },1000);
// });
// console.log(ret);
// return ret.data;
// };
queryData().then(function(data){
console.log(data);
})
async function queryData1(){
var info = await axios.get('http://localhost:3000/data');
var ret = await axios.get('http://localhost:3000/data1'+'info.data');
console.log(ret);
return ret.data;
};
async function querydata(){
var ret = await new Promise(function(resolve,reject){
setTimeout(function(){
resolve("nihao")
},1000);
return ret
});
}
</script>
</body>
</html>
处理多个异步请求结果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./axios/axios.js"></script>
<script>
/**
* async,await处理多个异步任务
* */
// 设置默认url
axios.defaults.baseURL = "http://localhost:3000";
async function querydata(){
var info = await axiso.get("/index");
var ret = await axiso.get("/index?inof="+info.data);
return ret.data;
}
querydata().then(data=>{
console.log(data);
})
</script>
</body>
</html>
网友评论