2024年js常见面试题——详解Promise使用与原理及实现过程(附源码),我是如何收割多家大厂offer的

最后

好了,这就是整理的前端从入门到放弃的学习笔记,还有很多没有整理到,我也算是边学边去整理,后续还会慢慢完善,这些相信够你学一阵子了。

做程序员,做前端工程师,真的是一个学习就会有回报的职业,不看出身高低,不看学历强弱,只要你的技术达到应有的水准,就能够得到对应的回报。

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

学习从来没有一蹴而就,都是持之以恒的,正所谓活到老学到老,真正懂得学习的人,才不会被这个时代的洪流所淘汰。

res => {
// promises 全部变为 fulfilled 状态的处理
},
err => {
// promises 中有一个变为 rejected 状态的处理
}
)

race方法

Promise.race 和 Promise.all 类似,只不过这个函数会在 promises 中第一个 promise 的状态扭转后就开始后面的处理(fulfilled、rejected 均可)

const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(‘promise1’)
}, 100)
})
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(‘promise2’)
}, 1000)
})
const promises = [promise1, promise2]

Promise.race(promises).then(
res => {
// 此时只有 promise1 resolve 了,promise2 仍处于 pending 状态
},
err => {}
)

四、配合 async await 使用

现在的开发场景中我们大多会用 async await 语法糖来等待一个 promise 的执行结果,使代码的可读性更高。async 本身是一个语法糖,将函数的返回值包在一个 promise 中返回。

// async 函数会返回一个 promise
const p = async function f() {
return ‘hello world’
}
p.then(res => console.log(res)) // hello world

五、开发技巧

在前端开发上 promise 大多被用来请求接口,Axios 库也是开发中使用最频繁的库,但是频繁的 try catch 扑捉错误会让代码嵌套很严重。考虑如下代码的优化方式

const getUserInfo = async function() {
return new Promise((resolve, reject) => {
// resolve() || reject()
})
}
// 为了处理可能的抛错,不得不将 try catch 套在代码外边,
// 一旦嵌套变多,代码可读性就会急剧下降
try {
const user = await getUserInfo()
} catch (e) {}

好的处理方法是在异步函数中就将错误 catch,然后正常返回,如下所示 👇

const getUserInfo = async function() {
return new Promise((resolve, reject) => {
// resolve() || reject()
}).then(
res => {
return [res, null] // 处理成功的返回结果
},
err => {
return [null, err] // 处理失败的返回结果
}
)
}

const [user, err] = await getUserInfo()
if (err) {
// err 处理
}

// 这样的处理是不是清晰了很多呢

六、Promise 源码实现

知识的学习需要知其然且知其所以然,所以通过一点点实现的一个 promise 能够对 promise 有着更深刻的理解。

(1)首先按照最基本的 promise 调用方式实现一个简单的 promise (基于 ES6 规范编写),假设我们有如下调用方式

new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
})
.then(
res => {
console.log(res)
return 2
},
err => {}
)
.then(
res => {
console.log(res)
},
err => {}
)

我们首先要实现一个 Promise 的类,这个类的构造函数会传入一个函数作为参数,并且向该函数传入 resolve 和 reject 两个方法。
初始化 Promise 的状态为 pending。

class MyPromise {
constructor(executor) {
this.executor = executor
this.value = null
this.status = ‘pending’

const resolve = value => {
if (this.status === ‘pending’) {
this.value = value // 调用 resolve 后记录 resolve 的值
this.status = ‘fulfilled’ // 调用 resolve 扭转 promise 状态
}
}

const reject = value => {
if (this.status === ‘pending’) {
this.value = value // 调用 reject 后记录 reject 的值
this.status = ‘rejected’ // 调用 reject 扭转 promise 状态
}
}

this.executor(resolve, reject)
}

(2)接下来要实现 promise 对象上的 then 方法,then 方法会传入两个函数作为参数,分别作为 promise 对象 resolve 和 reject 的处理函数。
这里要注意三点:

  • then 函数需要返回一个新的 promise 对象
  • 执行 then 函数的时候这个 promise 的状态可能还没有被扭转为 fulfilled 或 rejected
  • 一个 promise 对象可以同时多次调用 then 函数

class MyPromise {
constructor(executor) {
this.executor = executor
this.value = null
this.status = ‘pending’
this.onFulfilledFunctions = [] // 存放这个 promise 注册的 then 函数中传的第一个函数参数
this.onRejectedFunctions = [] // 存放这个 promise 注册的 then 函数中传的第二个函数参数
const resolve = value => {
if (this.status === ‘pending’) {
this.value = value
this.status = ‘fulfilled’
this.onFulfilledFunctions.forEach(onFulfilled => {
onFulfilled() // 将 onFulfilledFunctions 中的函数拿出来执行
})
}
}
const reject = value => {
if (this.status === ‘pending’) {
this.value = value
this.status = ‘rejected’
this.onRejectedFunctions.forEach(onRejected => {
onRejected() // 将 onRejectedFunctions 中的函数拿出来执行
})
}
}
this.executor(resolve, reject)
}

then(onFulfilled, onRejected) {
const self = this
if (this.status === ‘pending’) {
/**

  • 当 promise 的状态仍然处于 ‘pending’ 状态时,需要将注册 onFulfilled、onRejected 方法放到 promise 的 onFulfilledFunctions、onRejectedFunctions 备用
    */
    return new MyPromise((resolve, reject) => {
    this.onFulfilledFunctions.push(() => {
    const thenReturn = onFulfilled(self.value)
    resolve(thenReturn)
    })
    this.onRejectedFunctions.push(() => {
    const thenReturn = onRejected(self.value)
    resolve(thenReturn)
    })
    })
    } else if (this.status === ‘fulfilled’) {
    return new MyPromise((resolve, reject) => {
    const thenReturn = onFulfilled(self.value)
    resolve(thenReturn)
    })
    } else {
    return new MyPromise((resolve, reject) => {
    const thenReturn = onRejected(self.value)
    resolve(thenReturn)
    })
    }
    }
    }

对于以上完成的 MyPromise 进行测试,测试代码如下

const p = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
})

p.then(res => {
console.log(‘first then’, res)
return res + 1
}).then(res => {
console.log(‘first then’, res)
})

p.then(res => {
console.log(second then, res)
return res + 1
}).then(res => {
console.log(second then, res)
})

/**

  • 输出结果如下:
  • first then 1
  • first then 2
  • second then 1
  • second then 2
    */

(3)在 promise 相关的内容中,有一点常常被我们忽略,当 then 函数中返回的是一个 promise 应该如何处理?
考虑如下代码:

// 使用正确的 Promise
new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, 1000)
})
.then(res => {
console.log(‘外部 promise’)
return new Promise((resolve, reject) => {
resolve(内部 promise)
})
})
.then(res => {
console.log(res)
})

/**

  • 输出结果如下:
  • 外部 promise
  • 内部 promise
    */

通过以上的输出结果不难判断,当 then 函数返回的是一个 promise 时,promise 并不会直接将这个 promise 传递到下一个 then 函数,而是会等待该 promise resolve 后,将其 resolve 的值,传递给下一个 then 函数,找到我们实现的代码的 then 函数部分,做以下修改:

then(onFulfilled, onRejected) {
const self = this
if (this.status === ‘pending’) {
return new MyPromise((resolve, reject) => {
this.onFulfilledFunctions.push(() => {
const thenReturn = onFulfilled(self.value)
if (thenReturn instanceof MyPromise) {
// 当返回值为 promise 时,等该内部的 promise 状态扭转时,同步扭转外部的 promise 状态
thenReturn.then(resolve, reject)
} else {
resolve(thenReturn)
}
})
this.onRejectedFunctions.push(() => {
const thenReturn = onRejected(self.value)
if (thenReturn instanceof MyPromise) {
// 当返回值为 promise 时,等该内部的 promise 状态扭转时,同步扭转外部的 promise 状态
thenReturn.then(resolve, reject)
} else {
resolve(thenReturn)
}
})
})
} else if (this.status === ‘fulfilled’) {
return new MyPromise((resolve, reject) => {
const thenReturn = onFulfilled(self.value)
if (thenReturn instanceof MyPromise) {
// 当返回值为 promise 时,等该内部的 promise 状态扭转时,同步扭转外部的 promise 状态
thenReturn.then(resolve, reject)
} else {
resolve(thenReturn)
}
})
} else {
return new MyPromise((resolve, reject) => {
const thenReturn = onRejected(self.value)
if (thenReturn instanceof MyPromise) {
// 当返回值为 promise 时,等该内部的 promise 状态扭转时,同步扭转外部的 promise 状态
thenReturn.then(resolve, reject)
} else {
resolve(thenReturn)
}
})
}
}

(4) 之前的 promise 实现代码仍然缺少很多细节逻辑,下面会提供一个相对完整的版本,注释部分是增加的代码,并提供了解释。

class MyPromise {
constructor(executor) {
this.executor = executor
this.value = null
this.status = ‘pending’
this.onFulfilledFunctions = []
this.onRejectedFunctions = []
const resolve = value => {
if (this.status === ‘pending’) {
this.value = value
this.status = ‘fulfilled’
总结:

  • 函数式编程其实是一种编程思想,它追求更细的粒度,将应用拆分成一组组极小的单元函数,组合调用操作数据流;

  • 它提倡着 纯函数 / 函数复合 / 数据不可变, 谨慎对待函数内的 状态共享 / 依赖外部 / 副作用;

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

Tips:

其实我们很难也不需要在面试过程中去完美地阐述出整套思想,这里也只是浅尝辄止,一些个人理解而已。博主也是初级小菜鸟,停留在表面而已,只求对大家能有所帮助,轻喷🤣;

我个人觉得: 这些编程范式之间,其实并不矛盾,各有各的 优劣势

理解和学习它们的理念与优势,合理地 设计融合,将优秀的软件编程思想用于提升我们应用;

所有设计思想,最终的目标一定是使我们的应用更加 解耦颗粒化、易拓展、易测试、高复用,开发更为高效和安全

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值