【前端,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
    }
}
相关推荐
不好听61319 小时前
TypeScript 面试必会:工具类型全家桶,从 keyof 到手写 Partial
面试·typescript
嘟嘟071719 小时前
从入口到 CRUD:用 NestJS 的模块化与装饰器思想读懂一个后端应用
后端·typescript·nestjs
嘟嘟071719 小时前
TypeScript 工具类型通关:Pick、Omit、Partial、Record 区别与 Omit 等价实现一次讲清
设计模式·面试·typescript
何时梦醒20 小时前
TypeScript 工具类型一篇讲透:Pick、Omit、Partial、Exclude、Record、ReturnType、keyof
前端·面试·typescript
小林ixn20 小时前
TS 工具类型实战:Pick/Omit/Partial/Record 一次讲透,别再 Omit 反了
typescript·代码规范
苏灿烤鱼20 小时前
十个 CLI 坐进一间办公室,协调层靠得住吗?
typescript·github·agent
BreezeJiang20 小时前
别再死记 TypeScript 工具类型:看懂 Omit 的类型数据流
typescript
breeze jiang20 小时前
TypeScript 工具类型怎么记:从 Pick、Omit 到 keyof 与 Exclude 推导
linux·ubuntu·typescript
触底反弹20 小时前
🔥 NestJS 从零到实战:一个 Todos CRUD 搞懂企业级后端框架的核心设计
后端·typescript·nestjs
用户938515635071 天前
TypeScript 高级类型 + CSS 三列布局:从类型体操到样式工程的进阶之路
css·面试·typescript