19-简单理解JavaScript中的Promise:手写Promise实现
笔记+分享
在现代JavaScript开发中,异步编程是不可避免的一部分。为了更好地处理异步操作,ES6引入了Promise。Promise使得异步代码更具可读性和可维护性。通过手写一个完整的Promise实现,可以帮助你更深入地理解其工作原理。本文将详细介绍Promise的概念、用法及其在实际开发中的应用,并提供一个手写的Promise实现。
什么是Promise?
Promise是JavaScript中的一种对象,用于表示一个异步操作的最终完成(或失败)及其结果值。它有三种状态:
- Pending(待定):初始状态,既没有被兑现,也没有被拒绝。
- Fulfilled(已兑现):操作成功完成,并返回一个值。
- Rejected(已拒绝):操作失败,并返回一个原因。
手写Promise实现
我们将通过构建一个简化版的Promise实现来更好地理解其工作原理。
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(fn => fn());
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(fn => fn());
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
let promise2 = new MyPromise((resolve, reject) => {
if (this.state === 'fulfilled') {
setTimeout(() => {
try {
let x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
}
if (this.state === 'rejected') {
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
}
if (this.state === 'pending') {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
let x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
});
}
});
return promise2;
}
catch(onRejected) {
return this.then(null, onRejected);
}
static resolve(value) {
return new MyPromise((resolve, reject) => {
resolve(value);
});
}
static reject(reason) {
return new MyPromise((resolve, reject) => {
reject(reason);
});
}
static all(promises) {
return new MyPromise((resolve, reject) => {
let results = [];
let completed = 0;
const processResult = (index, value) => {
results[index] = value;
if (++completed === promises.length) {
resolve(results);
}
};
promises.forEach((promise, index) => {
MyPromise.resolve(promise).then(value => {
processResult(index, value);
}, reject);
});
});
}
static race(promises) {
return new MyPromise((resolve, reject) => {
promises.forEach(promise => {
MyPromise.resolve(promise).then(resolve, reject);
});
});
}
}
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise'));
}
let called = false;
if (x && (typeof x === 'object' || typeof x === 'function')) {
try {
let then = x.then;
if (typeof then === 'function') {
then.call(x, y => {
if (called) return;
called = true;
resolvePromise(promise2, y, resolve, reject);
}, reason => {
if (called) return;
called = true;
reject(reason);
});
} else {
resolve(x);
}
} catch (error) {
if (called) return;
called = true;
reject(error);
}
} else {
resolve(x);
}
}
关键点解释
- 状态管理:Promise有三种状态:
pending
、fulfilled
和rejected
。通过state
变量来管理当前Promise的状态。 - 回调队列:使用两个数组
onFulfilledCallbacks
和onRejectedCallbacks
来存储在pending
状态时注册的回调函数。 - resolve和reject:
resolve
函数将Promise状态从pending
变为fulfilled
,并执行所有成功回调;reject
函数将Promise状态从pending
变为rejected
,并执行所有失败回调。 - then方法:
then
方法返回一个新的Promise,并根据当前Promise的状态决定如何处理回调函数。 - resolvePromise函数:这个函数用来处理
then
方法中的链式调用,确保Promise的规范执行,防止循环引用等问题。
用法示例
const p1 = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('成功');
}, 1000);
});
p1.then(value => {
console.log(value); // 输出 "成功"
return new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('链式调用成功');
}, 1000);
});
}).then(value => {
console.log(value); // 输出 "链式调用成功"
}).catch(error => {
console.error(error);
});
通过这个手写的Promise实现,你可以更好地理解Promise的内部工作机制,并在实际开发中灵活运用Promise来处理异步操作。希望这篇博客能帮助你深入理解JavaScript中的Promise。