前端那些事

vuePress-theme-reco chenpeng    2020 - 2021
前端那些事 前端那些事

Choose mode

  • dark
  • auto
  • light
首页
文章目录
  • Browser
  • CSS
  • ES6
  • JavaScript
  • Network
  • TypeScript
  • Vue
  • Vue3
  • Webpack
标签
时间轴
GitHub
author-avatar

chenpeng

85

Article

25

Tag

首页
文章目录
  • Browser
  • CSS
  • ES6
  • JavaScript
  • Network
  • TypeScript
  • Vue
  • Vue3
  • Webpack
标签
时间轴
GitHub
  • ES6-异步

    • Generator生成器函数
    • Promise
    • async与await

async与await

vuePress-theme-reco chenpeng    2020 - 2021

async与await

chenpeng 2020-11-30 ES6异步

async 和 await 两种语法结合可以让异步代码像同步代码一样

# 1.async

  • async 函数的返回值为 promise 对象
  • promise 对象的结果由 async 函数执行的返回值决定
async function fn() {}
1

1.返回一个非 promise 类型的对象时,返回的结果是一个成功的 promise 对象

async function fn() {
    return '用户数据';
}
const result = fn();
console.log(result);
1
2
3
4
5

image-20200712160047801

2.抛出错误时,返回的结果是一个失败的 promise 对象

async function fn() {
    throw new Error('出错了');
}
const result = fn();
console.log(result);
1
2
3
4
5

image-20200712160607211

3.直接返回一个 promise 对象

async function fn() {
    return new Promise((resolve, reject) => {
        resolve('成功');
    })
}
const result = fn();
console.log(result);
1
2
3
4
5
6
7

image-20200712160813377

# 2.await

  • await 必须写在 async 函数中
  • await 右侧的表达式一般为 promise 对象
  • await 返回的是 promise 成功的值
  • await 的 promise 失败了,就会抛出异常,需要通过 try...catch 捕获处理
const p = new Promise((resolve, reject) => {
    resolve('成功');
});
async function fn() {
    let result = await p;
    console.log(result);
}
fn(); // 成功
1
2
3
4
5
6
7
8
const p = new Promise((resolve, reject) => {
    reject('失败');
});
async function fn() {
    try{
        let result = await p;
        console.log(result);
    }catch (e) {
        console.log(e);
    }
}
fn(); // 失败
1
2
3
4
5
6
7
8
9
10
11
12