前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >async + await 的理解和用法(Promise)

async + await 的理解和用法(Promise)

作者头像
很酷的站长
发布2022-12-16 21:50:53
1.7K0
发布2022-12-16 21:50:53
举报

1. 前言

async/await 是 ES7 提出的基于 Promise (ES6 中提出的) 的解决异步的最终方案

async + await 的作用: 简化 promise 的异步操作,把 promise 的异步操作编程变为同步的写法

async 将一个函数标记为异步函数,await 需要在异步函数中使用,标记当前操作是异步操作

async + await 必须配合 promise 使用,同时 async 和 await 必须一起使用。即 await 必须在 async 标记的函数中使用

2. 获取成功的结果

在 vue 脚手架和 uniapp 中经常使用的写法

代码语言:javascript
复制
function getProfile() {
    return new Promise((resolve, reject) => {
        // 使用定时器模拟接口请求
        setTimeout(() => {
            resolve({
                code: 200,
                msg: "用户信息",
                data: {
                    id: 1,
                    name: "liang"
                }
            })
        }, 3000);
    });
}
// 以下代码会执行 输入 123 再执行输出 res
function loadData() {
    getProfile().then(res => {
        console.log(res);
    })
    console.log(123);
}
// 下面写法会使 getProfile() 先执行
// 等待三秒后执行完再把得到的结果赋值给左边的res,然后再继续往下执行
async function loadData() {
    const res = await getProfile()
    console.log(res);
    console.log(123);
}
3. 获取失败的结果

当 Promise 抛出错误信息时,控制台默认是直接抛出异常的

代码语言:javascript
复制
reject('接口请求失败')

可以使用 try … catch 捕获 promise 抛出的错误

代码语言:javascript
复制
try {
    const res = await getProfile()
    console.log(res);
} catch (error) {
    console.log('error: ', error);
}
4. 多个 Promise 的场景

使用 Promise

Promise.all 的参数是一个数组,数组的每一项是一个返回的 promise 的函数调用

代码语言:javascript
复制
Promise.all([getProfile(), getProfile()]).then(res => {
console.log(res, 'res');
})

使用 await

因为 Promise.all 返回的也是一个 Promise,所以也可以使用 await

代码语言:javascript
复制
async function loadData() {
const res = await Promise.all([getProfile(), getProfile()])
console.log(res);
}
5. async 标记函数

使用 async 标记一个函数,那么当调用这个函数时,该函数会返回一个 promise 对象

如果没有在 async 函数中 return ,那么 promise 对象的 resolve 就是 ?developer/article/2194437/undefined

如果在 async 函数中写了 return,那么 promise 对象的 resolve 就是 return 的值

如果 async 里的代码都是同步的,那么这个函数被调用就会同步执行

代码语言:javascript
复制
async function fn(){
  console.log('a')
}
fn()
console.log('b')
//a
//b
6. await 等待异步操作执行完成

右侧的表达式的结果就是 await 要等的东西,等到之后,对于 await 来说,分两个情况。是 promise 对象,不是 promise 对象

代码语言:javascript
复制
const res = await getProfile()

如果不是 promise 对象,await 会阻塞后面的代码,先执行 async 外面的同步代码,再回到 async 内部,把这个非 promise 的东西,作为 await 表达式的结果

代码语言:javascript
复制
function fn() {
    console.log(1)
    return 'this is return'
}
async function f1() {
    const res = await fn()
    console.log(2)
    console.log(res);
}
f1()
console.log(3)
//1
//3
//2
// this is return

如果 await 等到的是一个 promise 对象,await 也会暂停 async 后面的代码,先执行 async 外面的同步代码,等着 Promise 对象 fulfilled,然后把 resolve 的参数作为 await 表达式的运算结果

代码语言:javascript
复制
function fn() {
    console.log(1)
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('this is return')
        }, 1500);
    });
}
async function f1() {
    const res = await fn()
    console.log(2)
    console.log(res);
}
f1()
console.log(3)
//1
//3
//2
// this is return
6. async + await 相关文章推荐

async 和 await 【简书】: https://www.jianshu.com/p/b4fd76c61dc9

本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 前言
  • 2. 获取成功的结果
  • 3. 获取失败的结果
  • 4. 多个 Promise 的场景
  • 5. async 标记函数
  • 6. await 等待异步操作执行完成
  • 6. async + await 相关文章推荐
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com