【前端,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
    }
}
相关推荐
一生躺平的仔13 小时前
TypeScript入门(九)装饰器:TypeScript的"元编程超能力"
typescript
MiyueFE13 小时前
让我害怕的 TypeScript 类型 — — 直到我学会了这 3 条规则
前端·typescript
前端拿破轮14 小时前
😭😭😭看到这个快乐数10s,我就知道快乐不属于我了🤪
算法·leetcode·typescript
前端_ID林14 小时前
每个开发人员都应该知道的 TypeScript 技巧
typescript
奋飛16 小时前
TypeScript系列:第六篇 - 编写高质量的TS类型
javascript·typescript·ts·declare·.d.ts
BillKu11 天前
Vue3 + TypeScript + xlsx 导入excel文件追踪数据流转详细记录(从原文件到目标数据)
前端·javascript·typescript
小Lu的开源日常11 天前
Drizzle vs Prisma:现代 TypeScript ORM 的深度对比
数据库·typescript·前端框架
Shixaik11 天前
配置@为src
typescript·前端框架
BillKu11 天前
Vue3 + TypeScript合并两个列表到目标列表,并且进行排序,数组合并、集合合并、列表合并、list合并
vue.js·typescript·list
ze_juejin11 天前
Typescript中的继承示例
前端·typescript