【前端,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 之父的 7 个启示
前端·typescript
Din2 天前
主动取消的防抖
前端·javascript·typescript
决斗小饼干2 天前
跨语言移植手记:把 TypeScript 的 Codex SDK 请进 .NET 世界
前端·javascript·typescript
Wect2 天前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
IT星宿3 天前
开发一个 TypeScript 语言服务插件:让 RTK Query 的"跳转到定义"更智能
typescript·redux
不会敲代码14 天前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
不会敲代码14 天前
从零开始用 TypeScript + React 打造类型安全的 Todo 应用
前端·react.js·typescript
赵小胖胖5 天前
解决方案与原理解析:TypeScript 中 Object.keys() 返回 string[] 导致的索引类型丢失与优雅推导方案
typescript
minge6 天前
借助 Trae Builder 把 TypeScript 的碎片化学习记录整理成文档
typescript
骑着小黑马6 天前
从 Electron 到 Tauri 2:我用 3.5MB 做了个音乐播放器
前端·vue.js·typescript