Codog

关注微信公众号:Codog代码狗

0%

async/await与Promise

async/await是语法糖,可以让我们以同步代码的写法执行异步逻辑。

async/await语法

image

需要注意的是await后面的代码执行逻辑,几个示例

demo1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
async function async1() {
console.log("async1 start");
await async2();
console.log("async1 end");
}
async function async2() {
console.log("async2 end");
}

console.log("script start");
async1();
console.log("script end");

/**
* Result:
* script start
async1 start
async2 end
script end
async1 end
*/

demo2: 为了演示await async1的效果,外面又套了一层async方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(async function () {
async function async1() {
console.log("async1 start");
await async2();
console.log("async1 end");
}
async function async2() {
console.log("async2 end");
}

console.log("script start");
await async1();
console.log("script end");
})();

/**
* Result:
* script start
async1 start
async2 end
async1 end *这里因为await提前了*
script end
*/

与Promise的关系

关于捕获异常

try…catch无法捕获Promise的reject。而await则可以

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
try {
Promise.reject("promise error");
} catch {
// 控制台打出 Uncaught (in promise) promise error;说明未被捕获
console.log("get promise error");
}

(async function () {
try {
await Promise.reject("error");
} catch {
// 输出get async error
console.log("get async error");
}
})();