用promise和async、await封装一个类
时间: 2024-05-21 20:11:06 浏览: 75
class MyPromise {
constructor(fn) {
this.state = "pending";
this.value = undefined;
this.callbacks = [];
try {
fn(this.onResolve.bind(this));
} catch (error) {
this.onReject(error);
}
}
onResolve(value) {
if (this.state === "pending") {
this.state = "fulfilled";
this.value = value;
this.callbacks.forEach((callback) => {
callback.onFulfilled(value);
});
}
}
onReject(error) {
if (this.state === "pending") {
this.state = "rejected";
this.value = error;
this.callbacks.forEach((callback) => {
callback.onRejected(error);
});
}
}
then(onFulfilled, onRejected) {
if (this.state === "fulfilled") {
onFulfilled(this.value);
} else if (this.state === "rejected") {
onRejected(this.value);
} else {
this.callbacks.push({ onFulfilled, onRejected });
}
}
}
class MyAsync {
static async series(tasks) {
let results = [];
for (let task of tasks) {
const result = await new Promise((resolve, reject) =>
task((err, result) => (err ? reject(err) : resolve(result)))
);
results.push(result);
}
return results;
}
static async parallel(tasks) {
const promises = tasks.map((task) => new Promise((resolve, reject) =>
task((err, result) => (err ? reject(err) : resolve(result)))
));
return await Promise.all(promises);
}
}
阅读全文