zl程序教程

您现在的位置是:首页 >  Python

当前栏目

async await语句

2023-02-25 18:27:40 时间

简述

async一般配合await才有用。可简化promise,省去.then的写法

在一个被async声明的函数内,await可把一个异步任务(promise)转为同步,阻塞后面的同步代码,让它们等待被await的任务执行完毕,再继续执行

await相当于Promise.then,同一作用域下await后面的内容全部作为then中回调的内容

async函数返回值

async函数的返回值为Promise对象,所以它可以调用then方法

1async function fn() {
2  return "async"
3}
4fn().then(res => {
5  console.log(res) // "async"
6})
7

深入理解await:

代码执行到await,有两种情况:

  • 场景一:await后面不是promise对象

先把await执行完(把这个非promise的东西,作为 await表达式的结果)。然后去把async外面的同步代码执行完,再回到async执行await后面被暂停的代码。

1console.log(1);
2
3async function fn() {
4  console.log(2);
5  await console.log(9);
6  console.log(10);
7}
8fn();
9
10console.log(3);
11
12// 1
13// 2
14// 9
15// 3
16// 10
  • 场景二:await后面是Promise对象(最常用)

执行完promise里的代码后,先去执行async外面的同步代码,再回来等待promise对象的状态改变,拿到结果,再执行后面被暂停的代码(如果状态不变则不会执行后面暂停的代码)

1console.log(1);
2
3async function fn() {
4  console.log(2);
5  await new Promise((resolve) => {
6    console.log(9);
7    setTimeout(() => {
8      resolve();
9    }, 3000);
10  });
11  console.log(10);
12}
13fn