js中promise介绍,原理,手动实现

动态 未结 0 94
小小草
小小草 LV1 2023年9月23日 23:40 发表
Promise 是一种用于处理异步操作的 JavaScript 对象,它可以将异步操作转换为同步操作,从而更加方便地进行错误处理和代码组织。Promise 的原理是基于状态机和回调函数。 Promise 有三种状态:pending(等待中)、fulfilled(已完成)和rejected(已拒绝)。当 Promise 被创建时,它的状态为 pending。当异步操作完成时,Promise 的状态会变为 fulfilled,并且会执行对应的成功回调函数。如果异步操作失败,则 Promise 的状态会变为 rejected,并且会执行对应的失败回调函数。 手动实现一个简单的 Promise: ```javascript class MyPromise { constructor(executor) { this.state = 'pending'; this.value = undefined; this.reason = undefined; this.onFulfilledCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.state === 'pending') { this.state = 'fulfilled'; this.value = value; this.onFulfilledCallbacks.forEach((callback) => callback(this.value)); } }; const reject = (reason) => { if (this.state === 'pending') { this.state = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach((callback) => callback(this.reason)); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } then(onFulfilled, onRejected) { const promise2 = new MyPromise((resolve, reject) => { if (this.state === 'fulfilled') { setTimeout(() => { try { const x = onFulfilled(this.value); resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } if (this.state === 'rejected') { setTimeout(() => { try { const x = onRejected(this.reason); resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } if (this.state === 'pending') { this.onF
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复