ES8引入了async函数,使得异步操作变得更加方便。简单说来,它就是Generator函数的语法糖。
async function asyncFunc(params) {
const result1 = await this.login()
const result2 = await this.getInfo()
}
是不是更加简洁易懂呢?
变体
异步函数存在以下四种使用形式:
- 函数声明:
async function foo() {}
- 函数表达式:
const foo = async function() {}
- 对象的方式:
let obj = { async foo() {} }
- 箭头函数:
const foo = async () => {}
常见用法汇总
处理单个异步结果:
async function asyncFunc() {
const result = await otherAsyncFunc();
console.log(result);
}
顺序处理多个异步结果:
async function asyncFunc() {
const result1 = await otherAsyncFunc1();
console.log(result1);
const result2 = await otherAsyncFunc2();
console.log(result2);
}
并行处理多个异步结果:
async function asyncFunc() {
const [result1, result2] = await Promise.all([
otherAsyncFunc1(),
otherAsyncFunc2()
]);
console.log(result1, result2);
}
处理错误:
async function asyncFunc() {
try {
await otherAsyncFunc();
} catch (err) {
console.error(err);
}
}