目录
1.概念
2.本质
3.语法
4.特点
5.async基本使用
6.async里的await普通函数返回值
7.async里的await Promise函数成功返回值
8.async里的await Promise函数失败返回值
9.解决async里的await Promise函数失败后不执行下面内容
1.概念
真正意义上解决异步回调的问题,同步流程表达异步操作
2.本质
Generator的语法糖
3.语法
async function foo(){
await 异步操作;
await 异步操作;
}
4.特点
1、不需要像Generator去调用next 方法,遇到await等待,当前的异步操作完成就往下执行
2、返回的点是promise对象,可以用then 万法进行下一步操作
3、async取代Generator西数的星号*,await取Generator的yield
4、语意上更为明确,使用简单
5.async基本使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
// async 基本用法
async function foo(){
return new Promise(resolve => {
setTimeout(resolve,2000)
})
}
async function testAsync(){
console.log("开始执行",new Date().toTimeString())
await foo();
console.log("开始执行",new Date().toTimeString())
}
testAsync();
</script>
</body>
</html>
6.async里的await普通函数返回值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>async</title>
</head>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function test2(){
return {code:200,data:{}}
}
// async 里面 await 返回值
async function asyncPrint(){
let res = await test2();
console.log(res)
}
asyncPrint()
</script>
</body>
</html>
7.async里的await Promise函数成功返回值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>async</title>
</head>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
// async 里面 await 返回值
async function asyncPrint(){
let res = await Promise.resolve({"key":"value"});
console.log(res)
}
asyncPrint()
</script>
</body>
</html>
8.async里的await Promise函数失败返回值
解决报错后面代码不执行,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>async</title>
</head>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
// async 里面 await 返回值
async function asyncPrint(){
let res = await Promise.reject({"code":"400"});
console.log(res)
}
asyncPrint()
</script>
</body>
</html>
9.解决async里的await Promise函数失败后不执行下面内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>async</title>
</head>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
async function test(obj){
return new Promise((resolve,reject)=>{
// 模拟异常
// key=1为异常,异常处理也用resolve()函数
if(obj.key==1){
resolve(false);
}else{
resolve({code:200})
}
})
}
// async 里面 await 返回值
async function asyncPrint(){
let res = await test({key:1});
console.log(res)
console.log("12313")
}
asyncPrint()
</script>
</body>
</html>