以下是一个用 JavaScript 实现的简单 Promise 并打印结果的示例代码:
class MyPromise {
constructor(executor) {
this.status = 'pending';
this.value = undefined;
this.reason = undefined;
const resolve = (value) => {
if (this.status === 'pending') {
this.status = 'fulfilled';
this.value = value;
}
};
const reject = (reason) => {
if (this.status === 'pending') {
this.status = 'ejected';
this.reason = reason;
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
}
// 创建一个 Promise 实例
const myPromise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 成功了!');
}, 1000);
});
// 监听 Promise 的状态变化
myPromise.then((result) => {
console.log(result);
}).catch((error) => {
console.error(error);
});