【前端,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
    }
}
相关推荐
Dignity_呱7 小时前
别在傻傻分不清any void never unknown的场景啦
前端·vue.js·typescript
烛阴10 小时前
模块/命名空间/全局类型如何共存?TS声明空间终极生存指南
前端·javascript·typescript
漫谈网络11 小时前
TypeScript 编译 ES6+ 语法到兼容的 JavaScript介绍
javascript·typescript·es6
zhfy啊1 天前
数组转哈希映射工具函数封装(toMap方法)
前端·typescript
William Dawson1 天前
【从前端到后端导入excel文件实现批量导入-笔记模仿芋道源码的《系统管理-用户管理-导入-批量导入》】
java·前端·笔记·elementui·typescript·excel
陌陌6231 天前
使用TypeScript构建一个最简单的MCP服务器
服务器·javascript·typescript
testleaf2 天前
React知识点梳理
前端·react.js·typescript
Moment2 天前
不是只有服务能分布,类型也能分布:解密 TypeScript 分布式条件类型
前端·javascript·typescript
狂炫一碗大米饭2 天前
关于 TS 中的装饰器
typescript·代码规范
开开心心就好3 天前
免费批量文件重命名软件
vue.js·人工智能·深度学习·typescript·pdf·excel·less