抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

async 函数可能包含 0 个或者多个 await 表达式。await 表达式会暂停整个 async 函数的执行进程并出让其控制权,只有当其等待的基于 promise 的异步操作被兑现或被拒绝之后才会恢复进程。promise 的解决值会被当作该 await 表达式的返回值。使用 async/await 关键字就可以在异步代码中使用普通的 try/catch 代码块。

备注

await关键字只在 async 函数内有效。如果你在 async 函数体之外使用它,就会抛出语法错误 SyntaxError

备注

async/await的目的为了简化使用基于 promise 的 API 时所需的语法。async/await 的行为就好像搭配使用了生成器和 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
27
28
29
30
31
32
33
34
35
36
37
let count = 0;
function request (url) {
return new Promise(resolve => {
setTimeout(() => {
resolve(url + count ++);
}, 500);
});
}

// 使用async/await语法糖
// async function run () {
// const res1 = await request('1111');
// const res2 = await request(res1);
// console.log(res2);
// }

// run();

// 基于生成器函数模拟async/await
function* generate() {
const res = yield request('1111');
const res2 = yield request(res);
console.log(res2);
}
// 使用递归实现连续调用
function run () {
const g = generate();
function exec (params) {
const { value, done } = g.next();
if (!done) {
value.then(res => exec(res));
}
}
exec();
}

run();

评论