# 语法结构
- 异步函数声明式
async function name([param]){} |
- 异步函数表达式
let name = async function([param]){} |
用法示例:
async function myAsync() { | |
return "hello world"; | |
} | |
let promise = myAsync(); | |
promise.then((value) => { | |
console.log(value); // hello world | |
}); |
# await 表达式
await
表达式用于等待一个 Promise
对象,它只能在异步函数中使用。
[return_value] = await expression; |
return_value
返回 Promise 对象的处理结果。如果等待的不是 Promise 对象,则返回该值本身。
expression
一个 Promise 对象或者任何要等待的值
function createPromise() { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve("执行成功了!"); | |
}, 200); | |
}); | |
} | |
async function myAsync() { | |
console.log("当前异步函数"); | |
var result = await createPromise(); | |
console.log(result); | |
} | |
myAsync(); // |
通过 await 处理报错。
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
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(); // one two three |
在处理多个 promise 时不会因为执行执行时间不同而导致的结果不同。