用js实现一个promise
时间: 2024-03-25 09:12:12 浏览: 63
以下是一个简单的Promise实现:
```
function MyPromise(fn) {
var state = 'pending';
var value;
var deferred;
function resolve(newValue) {
value = newValue;
state = 'resolved';
if(deferred) {
handle(deferred);
}
}
function reject(reason) {
value = reason;
state = 'rejected';
if(deferred) {
handle(deferred);
}
}
function handle(handler) {
if(state === 'pending') {
deferred = handler;
return;
}
var handlerCallback;
if(state === 'resolved') {
handlerCallback = handler.onResolved;
} else {
handlerCallback = handler.onRejected;
}
if(!handlerCallback) {
if(state === 'resolved') {
handler.resolve(value);
} else {
handler.reject(value);
}
return;
}
try {
var result = handlerCallback(value);
handler.resolve(result);
} catch(err) {
handler.reject(err);
}
}
this.then = function(onResolved, onRejected) {
return new MyPromise(function(resolve, reject) {
handle({
onResolved: onResolved,
onRejected: onRejected,
resolve: resolve,
reject: reject
});
});
};
fn(resolve, reject);
}
```
可以使用以下方式来使用Promise:
```
var promise = new MyPromise(function(resolve, reject) {
// 异步操作
setTimeout(function() {
resolve('Hello, world!');
}, 1000);
});
promise.then(function(result) {
console.log(result);
});
```
在这个例子中,我们创建了一个新的MyPromise对象,并传入一个函数作为参数。该函数会在异步操作完成后调用resolve函数来设置Promise的状态为resolved,并传入结果值。然后,我们调用then方法来注册一个回调函数,该函数会在Promise被resolve后被调用,结果值会作为参数传入该函数。在这个例子中,我们使用setTimeout函数来模拟异步操作。当Promise被resolve后,我们会在控制台打印出结果值。
阅读全文