返回
Promise的全过程
前端
2023-11-07 17:34:10
Promise的基本概念
Promise对象是CommonJS工作组提出的一种规范,目的是为异步操作提供统一接口。首先,它是一个对象,也就是说与其他JavaScript对象的用法,没有什么两样;其次,它起到代理作用(proxy),充当异步操作与回调函数之间的中介。它使得异步操作具备同步操作的接口,使得你可以像操作同步操作一样操作异步操作。
如何手动实现一个满足promises-aplus-tests的Promise
以下是一个手动实现的Promise类:
class Promise {
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((callback) => {
callback(value);
});
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach((callback) => {
callback(reason);
});
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
return new Promise((resolve, reject) => {
if (this.state === 'fulfilled') {
setTimeout(() => {
try {
const value = onFulfilled(this.value);
resolve(value);
} catch (error) {
reject(error);
}
}, 0);
} else if (this.state === 'rejected') {
setTimeout(() => {
try {
const reason = onRejected(this.reason);
resolve(reason);
} catch (error) {
reject(error);
}
}, 0);
} else {
this.onFulfilledCallbacks.push((value) => {
setTimeout(() => {
try {
const value = onFulfilled(value);
resolve(value);
} catch (error) {
reject(error);
}
}, 0);
});
this.onRejectedCallbacks.push((reason) => {
setTimeout(() => {
try {
const reason = onRejected(reason);
resolve(reason);
} catch (error) {
reject(error);
}
}, 0);
});
}
});
}
catch(onRejected) {
return this.then(undefined, onRejected);
}
finally(onFinally) {
return this.then(
(value) => {
onFinally();
return value;
},
(reason) => {
onFinally();
throw reason;
}
);
}
}
Promise的优点和局限性
Promise的优点有很多,包括:
- 使得异步操作更易于管理和编写。
- 提高代码的可读性和可维护性。
- 可以轻松地将异步操作串联起来。
Promise的局限性也有一些,包括:
- 只能处理单一的值,如果要处理多个值,需要使用数组或对象。
- 不能取消正在进行的异步操作。
- 如果Promise对象被回收,则会引发错误。
总体来说,Promise是一个非常有用的工具,可以极大地简化异步操作的处理。