在 JavaScript 中,Promise 是一种用于异步编程的对象。它允许你将异步操作的代码写在一起,并在操作完成时得到通知。Promise 的主要作用是使异步操作的代码更具可读性和可维护性,并让你能够更好地控制异步操作的流程。
手写 Promise 的原理其实就是实现了一个类似 Promise 的对象。这个对象能够存储异步操作的状态,并在操作完成时执行注册的回调函数。在这个对象中,通常会包含以下几个重要的属性和方法:
state
属性:用于存储异步操作的状态,可以取 "pending"、"fulfilled" 和 "rejected" 三种值。value
属性:用于存储异步操作的结果值。callbacks
数组:用于存储已注册的回调函数。transition
函数:用于更新state
和value
属性的值。then
方法:用于注册回调函数,并返回一个新的 Promise 对象。
function myPromise(executor) {
// Store the state of the promise
let state = "pending";
// The resolved value of the promise
let value = undefined;
// The array of registered callbacks
let callbacks = [];
// A function to transition the state of the promise
function transition(newState, newValue) {
// Update the state and value
state = newState;
value = newValue;
// Execute any registered callbacks
if (state === "fulfilled") {
callbacks.forEach(cb => cb(value));
}
}
// The "then" method of the promise
function then(onFulfilled) {
// Return a new promise
return new myPromise(function(resolve) {
// Register the callback for the new promise
callbacks.push(function(value) {
// Resolve the new promise with the result of the callback
resolve(onFulfilled(value));
});
// If the promise is already fulfilled, execute the callback immediately
if (state === "fulfilled") {
resolve(onFulfilled(value));
}
});
}
// Execute the executor function with the resolve and reject functions
executor(function(newValue) {
transition("fulfilled", newValue);
});
// Return the "then" method
return {
then: then
};
}
下面我们来看一个使用手写的 myPromise
的示例。在这个例子中,我们实现了一个简单的计时器,它会在指定的时间后触发一个回调函数。
function timer(delay) {
// Return a new promise
return new myPromise(function(resolve) {
// Wait for the specified delay
setTimeout(function() {
// Resolve the promise with the current time
resolve(Date.now());
}, delay);
});
}
// Start the timer
timer(1000)
// Register a callback to print the time
.then(function(time) {
console.log(time); // 1603444476266 (current time in ms)
});