【前端,TypeScript】TypeScript速成(九):async-await 语法糖

async-await 语法糖

可以使用 async-await 来管理 Promise,下例重写上一节使用 Promise + then 的形式计算 ( 2 + 3 ) × ( 4 + 5 ) (2+3) \times (4+5) (2+3)×(4+5):

typescript 复制代码
function add(a: number, b: number): Promise<number>{
    return new Promise(
        (resolve, reject) => {
            if(b % 17 == 0) {
                reject(`bad number ${b}`)
            }
            setTimeout(
                () => {
                    resolve(a + b)
                }, 2000
            )
        }
    )
}

function mul(a: number, b: number): Promise<number>{
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(a * b)
        }, 3000)
        // resolve(a * b)
    })
}

// (2+3)*(4+5)
async function calc() {
    const a = await add(2, 3)   // 等到加法 add 之后, 将结果赋予 a
    // await 必须在 async function 当中使用
    console.log('2 + 3', a)
    const b = await add(4, 5)
    console.log('4 + 5', b)
    const c = await mul(a, b)
    console.log('a * b', c)
}

calc()

// output
[LOG]: "2 + 3",  5 
[LOG]: "4 + 5",  9 
[LOG]: "a * b",  45 

await 所做的工作是异步等待,它相当于语法糖,等价于 add(2, 3).then(... ... ...)。

如果将 c 作为返回值返回,那么 calc 的类型是Promise<number>。

上述片段存在的一个问题是,使用两个 await 仍然是串行的计算,我们希望并行地执行两个加法,方法仍然是 await 一个 Promise.all:

typescript 复制代码
async function calc() {
    try {
        const [a, b] = await Promise.all([add(2, 3), add(4, 5)])
        console.log('2 + 3', a)
        console.log('4 + 5', b)
        return await mul(a, b)
    } catch (err) {
        console.log("caught err", err)
        return undefined
    }
}
相关推荐
RuoyiOffice2 小时前
Vue3+TypeScript 企业管理平台统一UI:新增一个模块,为什么还要重新调样式?
spring boot·typescript·vue3·组件化开发·企业管理软件·ruoyi office·统一ui
Shockang1 天前
TanStack Router 实战:URL 校验、Loader 与路由权限
typescript·react·路由·前端开发·tanstack router
TYC91 天前
Mac创建Vue3+TypeScript或者React+TypeScript项目
前端·javascript·typescript
fbincon2 天前
Claude Code 自定义状态栏工具:安装、配置与 Subagent 状态展示
python·typescript·claude·claude-code·statusline
何何____2 天前
TypeScript 函数类型兼容性
前端·javascript·typescript
VimorphTech2 天前
React 任务轮询,为什么不能只写一个 setInterval?
javascript·typescript
const_qiu3 天前
第二章 2.6:初始化 NestJS 服务端 —— TypeScript 后端框架体验
前端·javascript·typescript
RobinDevNotes3 天前
一套代码发布到十几个平台:Cocos入门速览
typescript·c#·游戏开发
前端小L4 天前
typescript基础
typescript
濮水大叔4 天前
CabloyJS 的 AI 时刻:从 TypeScript 全栈框架到 AI 规范驱动开发
typescript·ai编程·全栈