- 你需要先了解 Promise。
- 本质是
Generator的语法糖。
参考
作用
简化
Promise的使用过程。让你的异步代码看起来像是同步的。
async
async位于函数字面量或函数表达式的前面(普通函数、立即执行函数和箭头函数均可),被修饰函数执行后会返回一个Promise对象。-
例子:
async function chloe() { console.log("chloe"); return 20; } 等价于 function chloe() { return new Promise((resolve, reject) => { console.log("chloe"); resolve(20); }); } 函数体内返回值则作为
resolve的参数。函数体内抛出错误,则错误信息作为
reject的参数。
await
await一定要位于async函数内部。await一般位于Promise对象之前,所以一般位于async函数执行的前面,但若是返回值为Promise对象的普通函数也可。await会拿到该对象的结果,也就是then中resolve或reject的参数。如果不是Promise对象,则直接返回对应的值。若
await后方不是Promise对象,则会将其用Promise.resolve包装后执行。await的执行会被强制等待至拿到结果,后续函数体内的代码执行被阻塞,函数本身不会阻塞整体代码。
async function chloe() {
console.log("chloe");
return 20;
}
async function taran() {
const age = await chloe(); chloe函数执行返回出一个Promise对象,await拿到该对象resolve的参数20,赋值给age
console.log("taran" + age);
}
taran(); chloe taran20
async function chloe() {
console.log("chloe");
throw 18;
}
async function taran() {
try {
const age = await chloe(); chloe函数执行返回出一个Promise对象,await拿到该对象reject的参数18
console.log("taran" + age); 不再执行
} catch (error) {
console.log("taran" + error); 捕获到错误信息18
}
}
taran(); chloe taran18