手写promise异步
时间: 2023-02-17 14:29:12 浏览: 38
手写Promise异步的方法如下:
```
// 定义Promise构造函数
function MyPromise(fn) {
// 状态机,初始化为pending
var state = 'pending';
// 成功结果
var value = null;
// 失败原因
var reason = null;
// 成功回调函数队列
var successCallback = [];
// 失败回调函数队列
var failCallback = [];
// resolve方法
function resolve(newValue) {
if (state === 'pending') {
state = 'fulfilled';
value = newValue;
successCallback.forEach(function(cb) {
cb(value);
});
}
}
// reject方法
function reject(newReason) {
if (state === 'pending') {
state = 'rejected';
reason = newReason;
failCallback.forEach(function(cb) {
cb(reason);
});
}
}
// then方法
this.then = function(onFulfilled, onRejected) {
if (state === 'fulfilled') {
onFulfilled(value);
}
if (state === 'rejected') {
onRejected(reason);
}
if (state === 'pending') {
successCallback.push(onFulfilled);
failCallback.push(onRejected);
}
}
// 执行fn函数
fn(resolve, reject);
}
```
使用方式为:
```
var promise = new MyPromise(function(resolve, reject) {
setTimeout(function() {
resolve('成功');
}, 1000);
});
promise.then(function(value) {
console.log(value);
}, function(reason) {
console.log(reason);
});
```
这样就实现了一个简单的promise异步.
阅读全文
相关推荐
















