async-await和promise.then()的区别和用法

  • .then

    typescript 复制代码
    function getDataThen() {
        post({url: url, data: data}).then((res: any) => {
            //处理逻辑
            return data;//一般不需要
        }
    }
  • async await

    typescript 复制代码
    async function getDataAsync() {
        const res = await post({url: url, data: data});
        //处理逻辑
        return data;//一般不需要
    }
  • 大多数情况,两者都是在方法内部处理业务。如果不关心返回值,直接调用即可。如果需要返回值,他们的返回值都是promise而不是直接返回数据,需要再次处理,可以使用.then或者await,但是await必须在async方法内部使用。

    typescript 复制代码
    不关心返回值
    function search() {
      getDataThen();
      getDataAsync();
    }
    关心返回值
    function search() {
      getDataThen().then(res: any) => {
          //处理逻辑
      };
      getDataAsync().then(res: any) => {
          //处理逻辑
      };
    }
    async function search() {
      const res = await getDataAsync();
      //处理逻辑
      const res2 = await getDataThen();
      //处理逻辑
    }
  • await的后面跟的代码相当于.then内部,所以第二个请求如果必须在第一个请求返回时才开始执行,那么可以写在.then方法内部,或者跟在第一个请求的await后面

    typescript 复制代码
    function getDataThen() {
        post({url: url, data: data}).then((res: any) => {
            //处理逻辑
            post({url: url, data: data}).then((res: any) => {
            //处理逻辑
        }
        }
    }
    
    async function getDataAsync() {
        const res1 = await post({url: url, data: data});
        const res2 = await post({url: url, data: data});
    }
  • async支持请求并行,需要多个请求并行时,会更节省时间。

    typescript 复制代码
    const [data1, data2] = await Promise.all([
        getData1(),
        getData2()
    ]);

最近整理了一个 Spring Boot 2 + Java 8 + Vue 3 + NaiveUI 的员工管理系统,核心功能包括:

  • 滑块验证码登录
  • 登录认证 + JWT
  • RBAC 权限管理(动态菜单)
  • 操作日志记录
  • 员工/部门/职位/工资信息管理
  • 包含完整的运行文档

系统仅供学习使用,请勿用于任何商业用途。

有需要的朋友可以免费下载:

https://download.csdn.net/download/weixin_42485982/92947551

下载后如有问题,欢迎在评论区留言交流。

相关推荐
消失的旧时光-19438 天前
Kotlin 协程设计思想(四):launch、async、withContext 到底有什么区别?
java·kotlin·async·launch·withcontext·deferred
西凉的悲伤11 天前
Spring Boot 中 @Async(value = “alertThreadPool“) 是什么?为什么企业项目喜欢自定义线程池?
spring boot·多线程·async·异步
曲幽1 个月前
让 FastAPI Agent 思考不阻塞:手把手教你实现异步任务与后台处理方案
redis·python·agent·fastapi·web·async·celery·ai agent·backgroundtask
曲幽1 个月前
让FastAPI Agent真正记住你:聊聊会话记忆与持久化存储的落地实践
redis·python·postgresql·fastapi·web·chat·async·session·ai agent
曲幽1 个月前
用了loguru我才明白,Python日志还能这么写
python·logging·fastapi·web·async·loguru·handler·uvicorn
曲幽2 个月前
FastAPI + SQLAlchemy 2.0 通用CRUD操作手册 —— 从同步到异步,一次讲透
python·fastapi·web·async·sqlalchemy·session·crud·sync·with
曲幽2 个月前
FastAPI 生产环境避坑指南:用 Alembic 管理数据库迁移,别再手动改表结构了!
python·fastapi·web·async·sqlalchemy·env·alembic·migration
曲幽2 个月前
FastAPI服务半夜又挂了?先别急着重启,查查你的数据库连接池“池子”是不是漏了
python·prometheus·fastapi·web·async·sqlalchemy·connection·pool
曲幽2 个月前
FastAPI数据库ORM怎么选?我肝了三个Demo后,终于不再纠结了
python·fastapi·web·orm·async·sqlalchemy·sqlmodel·tortoise