【前端,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
    }
}
相关推荐
EndingCoder1 天前
配置 tsconfig.json:高级选项
linux·前端·ubuntu·typescript·json
We་ct2 天前
LeetCode 58. 最后一个单词的长度:两种解法深度剖析
前端·算法·leetcode·typescript
踢球的打工仔2 天前
typescript-类的访问权限public、private、protected
前端·javascript·typescript
We་ct2 天前
LeetCode 12. 整数转罗马数字:从逐位实现到规则复用优化
前端·算法·leetcode·typescript
EndingCoder2 天前
构建工具集成:Webpack 和 TypeScript
前端·webpack·typescript
前端之虎陈随易2 天前
前端通用插件开发工具unplugin v3.0.0发布
前端·typescript
孟无岐2 天前
【Laya】HttpRequest 网络请求
网络·typescript·游戏引擎·游戏程序·laya
meng半颗糖2 天前
vue3+typeScript 在线预览 excel,word,pdf
typescript·word·excel
wuhen_n2 天前
类型断言:as vs <> vs ! 的使用边界与陷阱
前端·javascript·typescript
哆啦A梦15882 天前
Vue3魔法手册 作者 张天禹 02
前端·vue.js·typescript