谈谈Promise,Promise基本实现原理是怎么样的
时间: 2023-11-14 10:07:48 浏览: 76
promise实现原理
Promise是一种异步编程的解决方案,它可以避免回调地狱,使得异步操作更加优雅和易于维护。Promise有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。当Promise处于pending状态时,可以转化为fulfilled或rejected状态,一旦状态确定就不可再改变。
Promise的基本实现原理是通过构造函数创建一个Promise对象,该对象包含一个then方法和一个catch方法。在Promise对象内部,有一个状态变量和一个结果变量,当异步操作完成后,会根据操作结果修改状态变量和结果变量,并且执行相应的回调函数。
下面是Promise的基本实现代码:
```
function Promise(fn) {
var state = 'pending';
var value = null;
var callbacks = [];
this.then = function(onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
handle({
onFulfilled: onFulfilled || null,
onRejected: onRejected || null,
resolve: resolve,
reject: reject
});
});
};
this.catch = function(onError) {
return this.then(null, onError);
};
function handle(callback) {
if (state === 'pending') {
callbacks.push(callback);
return;
}
var cb = state === 'fulfilled' ? callback.onFulfilled : callback.onRejected;
var next = state === 'fulfilled' ? callback.resolve : callback.reject;
if (!cb) {
next(value);
return;
}
try {
var ret = cb(value);
next(ret);
} catch (e) {
callback.reject(e);
}
}
function resolve(newValue) {
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then;
if (typeof then === 'function') {
then.call(newValue, resolve, reject);
return;
}
}
state = 'fulfilled';
value = newValue;
setTimeout(function() {
callbacks.forEach(function(callback) {
handle(callback);
});
}, 0);
}
function reject(reason) {
state = 'rejected';
value = reason;
setTimeout(function() {
callbacks.forEach(function(callback) {
handle(callback);
});
}, 0);
}
fn(resolve, reject);
}
```
阅读全文