首先看一个例子
<script type="text/javascript">
async function fn(){
let v = await new Promise((resolve,reject)=>{
setTimeout(()=>{
let a = 10;
resolve(10);
},2000);
});
console.log(v);
}
fn();
</script>
控制台两秒之后打印了10。
ES7 - async
- await 操作符 - async 函数
await 必须 在 async 函数中才能使用
await 后面可以是任意值,但是一般跟 Promise 对象
- Promise 的 resolve 方法的值就是 await 值
- Promise 的 reject 不会作为值返回,需要使用try...catch 进行捕获
看一个例子咯
<script type="text/javascript">
async function fn() {
try {
var v = await getValue(10);
console.log(v);
var w = await getValue(20);
console.log(w);
var y = await getValue(200);
console.log(y);
} catch(e) {
console.log(e);
}
}
function getValue(val) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (val < 100) {
resolve(val * 10);
} else {
reject('传入的值太大了');
}
}, 2000);
});
}
fn();
</script>