【前端,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
    }
}
相关推荐
RoyLin2 小时前
TypeScript设计模式:门面模式
前端·后端·typescript
RoyLin3 小时前
TypeScript设计模式:责任链模式
前端·后端·typescript
RoyLin3 小时前
TypeScript设计模式:装饰器模式
前端·后端·typescript
RoyLin4 小时前
TypeScript设计模式:复合模式
前端·后端·typescript
RoyLin4 小时前
TypeScript设计模式:策略模式
前端·后端·typescript
RoyLin6 小时前
TypeScript设计模式:桥接模式
前端·后端·typescript
RoyLin8 小时前
TypeScript设计模式:抽象工厂模式
前端·后端·typescript
烛阴1 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
奔跑的蜗牛ing2 天前
Vue3 + Element Plus 输入框省略号插件:零侵入式全局解决方案
vue.js·typescript·前端工程化
光影少年2 天前
Typescript工具类型
前端·typescript·掘金·金石计划