js实现promise
Promise 的基本概念
Promise 是 JavaScript 中用于处理异步操作的对象,表示一个可能现在、也可能将来完成的操作及其结果值。Promise 有三种状态:
- Pending:初始状态,既未完成也未拒绝。
- Fulfilled:操作成功完成。
- Rejected:操作失败。
创建 Promise
Promise 构造函数接收一个执行器函数(executor),该函数包含 resolve 和 reject 两个参数:
const promise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
const success = true; // 模拟操作成功或失败
if (success) {
resolve('Operation completed successfully');
} else {
reject('Operation failed');
}
}, 1000);
});
Promise 的链式调用
Promise 通过 .then() 和 .catch() 方法处理成功或失败的结果,支持链式调用:
promise
.then((result) => {
console.log(result); // 输出成功结果
return 'Next step'; // 返回新值供下一个 then 使用
})
.then((nextResult) => {
console.log(nextResult); // 输出 'Next step'
})
.catch((error) => {
console.error(error); // 捕获错误
});
Promise 的静态方法
Promise 提供了一些静态方法用于处理多个 Promise:
-
Promise.all():等待所有 Promise 完成,或第一个失败。
Promise.all([promise1, promise2]) .then((results) => console.log(results)) .catch((error) => console.error(error)); -
Promise.race():返回第一个完成(成功或失败)的 Promise。Promise.race([promise1, promise2]) .then((result) => console.log(result)) .catch((error) => console.error(error)); -
Promise.resolve()和Promise.reject():快速创建已解决或已拒绝的 Promise。Promise.resolve('Immediate success').then(console.log); Promise.reject('Immediate failure').catch(console.error);
异步函数与 Promise
ES2017 引入的 async/await 语法糖简化了 Promise 的使用:

async function fetchData() {
try {
const result = await promise; // 等待 Promise 完成
console.log(result);
} catch (error) {
console.error(error);
}
}
fetchData();
实现一个简单的 Promise
以下是一个简化版的 Promise 实现(仅核心逻辑):
class SimplePromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach(callback => callback(value));
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.value = reason;
this.onRejectedCallbacks.forEach(callback => callback(reason));
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
if (this.state === 'fulfilled') {
onFulfilled(this.value);
} else if (this.state === 'rejected') {
onRejected(this.value);
} else {
this.onFulfilledCallbacks.push(onFulfilled);
this.onRejectedCallbacks.push(onRejected);
}
return this; // 简化版未实现链式调用
}
}
常见使用场景
-
HTTP 请求:结合
fetchAPI 使用 Promise 处理网络请求。fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); -
定时任务:用
setTimeout封装为 Promise。function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } delay(1000).then(() => console.log('1 second passed')); -
文件读写:Node.js 中
fs.promises模块提供 Promise 接口。const fs = require('fs').promises; fs.readFile('file.txt', 'utf8') .then(content => console.log(content)) .catch(error => console.error(error));






