ES7 async定义函数
语法:
async function 函数名()
{
await 异步操作
await 异步操作
}
1、将异步操作按同步操作执行,即上一步未执行完会阻塞当前函数的进程,不影响主线程
1、一般await后接promise对象
2、await 函数(); 返回值为函数的返回值
3、await Promise.resolve(内容); 返回值为resolve的参数;reject(内容)函数调用会报错,内容为reject中的参数
代码示例:
html文件:
<html ng-app='app' ng-controller='main' >
<head>
<meta charset="utf-8">
<meta name='viewport' content='width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0'>
<script src='jq/jquery-3.4.1.js'></script>
<style>
</style>
</head>
<body >
<script>
async function fun()
{
return new Promise(resolve=>{
setTimeout(resolve,2000);
})
}
async function fun2()
{
console.log('开始',new Date().toTimeString());
await fun();
//会两秒后再打印
console.log('结束',new Date().toTimeString());
}
fun2();
function fun4()
{
return 'jeff';
}
async function fun3()
{
let res=await fun4();
let res2=await Promise.resolve('promise')
console.log(res);
console.log(res2);
}
fun3();
//发送ajax请求
async function getNews(url)
{
return new Promise((resolve,reject)=>{
$.ajax({
method:'GET',
url:url,
dataType:'json',
success:function(res)
{
resolve(res);
}
})
})
}
async function sendXml()
{
let res=await getNews('http://localhost:3000/news?id=2');
console.log(res);
let res2=await getNews('http://localhost:3000'+res.commentsUrl);
console.log(res2);
}
sendXml();
</script>
</body>
</html>