返回
用心呵护一诺千金的Promise之约
前端
2023-12-12 23:31:06
了解Promise
Promise: 源自英语,含义为“承诺”、“保证”。而在计算机科学领域,Promise是一种异步编程的方式,它允许我们对异步操作的结果进行处理,并能避免回调函数带来的“回调地狱”。
构建Promise对象
为了更好地理解Promise,我们可以尝试亲手构建一个简单的Promise对象。
// Promise构造函数
function Promise(executor) {
this.state = 'pending'; // Promise的初始状态为"pending"
this.value = undefined; // Promise的值,在成功时为结果值,在失败时为错误值
this.reason = undefined; // Promise的失败原因
this.onFulfilledCallbacks = []; // 保存成功的回调函数
this.onRejectedCallbacks = []; // 保存失败的回调函数
// 执行器函数
try {
executor(resolve, reject); // 立即执行执行器函数,并将resolve和reject函数作为参数传入
} catch (err) {
reject(err); // 如果执行器函数抛出异常,则Promise转为失败态
}
}
// resolve函数,用于将Promise转为成功态
Promise.prototype.resolve = function(value) {
if (this.state !== 'pending') return; // 如果Promise不是"pending"态,则直接返回
this.state = 'fulfilled'; // 将Promise的状态改为"fulfilled"
this.value = value; // 将值保存到Promise的value属性中
this.onFulfilledCallbacks.forEach(callback => callback(this.value)); // 依次调用成功的回调函数
};
// reject函数,用于将Promise转为失败态
Promise.prototype.reject = function(reason) {
if (this.state !== 'pending') return; // 如果Promise不是"pending"态,则直接返回
this.state = 'rejected'; // 将Promise的状态改为"rejected"
this.reason = reason; // 将失败原因保存到Promise的reason属性中
this.onRejectedCallbacks.forEach(callback => callback(this.reason)); // 依次调用失败的回调函数
};
// then方法,用于添加成功或失败的回调函数
Promise.prototype.then = function(onFulfilled, onRejected) {
// 如果onFulfilled不是函数,则将其置为一个始终返回value的函数
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
// 如果onRejected不是函数,则将其置为一个始终返回reason的函数
onRejected = typeof onRejected === 'function' ? onRejected : reason => reason;
// 返回一个新的Promise对象
return new Promise((resolve, reject) => {
// 将成功的回调函数添加到onFulfilledCallbacks中
this.onFulfilledCallbacks.push(() => {
try {
// 调用成功的回调函数,并将结果作为参数传递给resolve函数
const result = onFulfilled(this.value);
resolve(result); // 将结果作为新的Promise的值
} catch (err) {
// 如果成功的回调函数抛出异常,则Promise转为失败态
reject(err);
}
});
// 将失败的回调函数添加到onRejectedCallbacks中
this.onRejectedCallbacks.push(() => {
try {
// 调用失败的回调函数,并将结果作为参数传递给resolve函数
const result = onRejected(this.reason);
resolve(result); // 将结果作为新的Promise的值
} catch (err) {
// 如果失败的回调函数抛出异常,则Promise转为失败态
reject(err);
}
});
});
};
结语
Promise不仅仅是一种编程工具,它更是一种编程思想。通过理解和掌握Promise,我们可以更优雅、更有效地处理异步编程问题。