【前端,TypeScript】TypeScript速成(八):Promise

Promise

前端编程是一个单线程的模型,但是其中包含许多异步的动作,异步的动作应该通过以下四步来完成:

  • 发起请求;
  • 事件处理函数结束;
  • 请求结束;
  • 进入回调函数;

上述的基于回调函数解决方案不够好,当事件请求过多时,可能会产生 Callback Hell 现象。使用 Promise 可以解决回调函数的问题。

Promise 的创建和使用

我们首先来看一个回调函数的例子,在这个例子中,我们在回调函数中进行简单的 number 加法:

typescript 复制代码
function add(a: number, b: number, callback: (res: number) => void): void {
    setTimeout(() => {
        callback(a + b)
    }, 2000)
}

add(2, 3, res => {
    console.log('2 + 3', res)
    add(res, 4, res2 => {
        console.log('2 + 3 + 4', res2)
    })
})

程序将先后输出:

typescript 复制代码
[LOG]: "2 + 3",  5 
[LOG]: "2 + 3 + 4",  9 

现在我们将回调函数改为 Promise:

typescript 复制代码
function add(a: number, b: number): Promise<number> {
    return new Promise(
        (resolve, reject) => {
            setTimeout(() => {
                resolve(a + b)
            }, 2000)
        }
    )
}

add(2, 3).then(res => {
    console.log('2 + 3', res)
})

可以使用 then 方法来完成多个计算结果的顺序打印:

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
add(2, 3).then(res => {
    console.log("2 + 3", res)
    return mul(res, 5)
}).then(res => {
    console.log("(2 + 3) * 4", res)
    return add(res, 5)
}).then(res => {
    console.log("(2 + 3) * 4 + 5", res)
    return add(res, 17)
}).then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
})

输出的结果是:

typescript 复制代码
[LOG]: "2 + 3",  5 
[LOG]: "(2 + 3) * 4",  25 
[LOG]: "(2 + 3) * 4 + 5",  30 
[LOG]: "bad number 17" 

需要注意的是,在使用 then 方法时,一定要在 then 作为参数的箭头函数当中将下一步要做的行为返回出去,这样才能创建多个 Promise。

同时等待多个 Promise

现在我们希望通过 Promise 来计算(2 + 3) * (4 + 5)的结果,使用 Promise.all 方法来完成:

typescript 复制代码
// (2+3)*(4+5)
Promise.all([add(2, 3), add(4, 5)]).then(res => {
    let [a, b] = res
    return mul(a, b)
}).then(res => {
    console.log("(2+3)*(4+5)", res)
})

可以使用 Promise.race 来看哪个 Promise 首先执行完毕:

typescript 复制代码
Promise.race([add(2, 3), add(4, 5)]).then(res => {
    console.log(res)
})

Promise 最大的用处是将多种行为串联起来,可以解决 Callback Hell 的问题。

相关推荐
難釋懷3 小时前
TypeScript-webpack
javascript·webpack·typescript
摸鱼仙人~2 天前
如何创建基于 TypeScript 的 React 项目
javascript·react.js·typescript
一生躺平的仔2 天前
TypeScript入门(九)装饰器:TypeScript的"元编程超能力"
typescript
MiyueFE2 天前
让我害怕的 TypeScript 类型 — — 直到我学会了这 3 条规则
前端·typescript
前端拿破轮2 天前
😭😭😭看到这个快乐数10s,我就知道快乐不属于我了🤪
算法·leetcode·typescript
前端_ID林2 天前
每个开发人员都应该知道的 TypeScript 技巧
typescript
奋飛2 天前
TypeScript系列:第六篇 - 编写高质量的TS类型
javascript·typescript·ts·declare·.d.ts
BillKu12 天前
Vue3 + TypeScript + xlsx 导入excel文件追踪数据流转详细记录(从原文件到目标数据)
前端·javascript·typescript
小Lu的开源日常12 天前
Drizzle vs Prisma:现代 TypeScript ORM 的深度对比
数据库·typescript·前端框架
Shixaik13 天前
配置@为src
typescript·前端框架