【前端,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
    }
}
相关推荐
烛衔溟12 小时前
TypeScript this 参数类型与全局 this
javascript·ubuntu·typescript
军军君0114 小时前
数字孪生监控大屏实战模板:云数据中心展示平台
前端·javascript·vue.js·typescript·前端框架·es6·echarts
|晴 天|16 小时前
评论系统与情感分析
前端·ai·typescript
烛衔溟17 小时前
TypeScript 函数重载(Overloads)
javascript·ubuntu·typescript
学以智用18 小时前
TypeScript 实战:从环境搭建到项目开发(完整指南)
typescript
遇见你...1 天前
TypeScript
前端·javascript·typescript
算是难了1 天前
Nestjs学习总结_3
前端·typescript·node.js
EaseUI1 天前
【Ease UI】2026-04-16 组件更新:新增组件 xly-flow-designer 流程设计器 基于warm-flow二次开发
typescript·前端框架·流程设计器·组件库·warmflow
千寻girling2 天前
被内推的面试 , 第一次
java·前端·python·面试·职场和发展·typescript·node.js
JustNow_Man2 天前
Bun 常用命令速查清单(TypeScript 编译篇)
前端·javascript·typescript