语法结构
- 异步函数声明式
1
| async function name([param]){}
|
- 异步函数表达式
1
| let name = async function([param]){}
|
用法示例:
1 2 3 4 5 6 7
| async function myAsync() { return "hello world"; } let promise = myAsync(); promise.then((value) => { console.log(value); });
|
await表达式
await
表达式用于等待一个Promise
对象,它只能在异步函数中使用。
1
| [return_value] = await expression;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function createPromise() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("执行成功了!"); }, 200); }); }
async function myAsync() { console.log("当前异步函数"); var result = await createPromise(); console.log(result); }
myAsync();
|
通过await处理报错。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| function createPromise() { return new Promise((resolve, reject) => { setTimeout(() => { reject("执行成功了!"); }, 200); }); }
async function myAsync() { console.log("当前异步函数"); try { var result = await createPromise(); } catch (e) { console.log("出错了", e); } console.log(result); }
myAsync();
|
处理多个promise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| let promise1 = new Promise((resolve, reject) => { setTimeout(() => { resolve("one"); }, 300); }); let promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve("two"); }, 200); }); let promise3 = new Promise((resolve, reject) => { setTimeout(() => { resolve("three"); }, 100); }); async function myAsync() { let result1 = await promise1; console.log(result1);
let result2 = await promise2; console.log(result2);
let result3 = await promise3; console.log(result3); } myAsync();
|
在处理多个promise时不会因为执行执行时间不同而导致的结果不同。