js简单手写实现下Prmoise
一、promise是什么
在JavaScript语言中,Promise是一种用于处理异步操作的对象,它代表了一个操作的最终完成(或失败)及其结果值。Promise提供了一种更加优雅和一致的方式来组织和管理异步代码,与传统的回调函数和回调地狱(callback hell)相比,Promise使得异步代码更易于阅读、理解和维护。
二、基本实现
核心思路点总结:
- Promise三种状态的记录(pendding、resolved、rejected)和变更(通过resolve和reject函数变更)
- 成功回调和失败回调函数的收集(在then中且pendding时候收集)
- 成功回调和失败回调函数的触发(resolve和reject函数中触发)
- then里自定义回调在什么时候触发(当状态变成resolved、rejected时候触发)
// 实现Promise
class MyPromise {
PENDING = 'pendding';
RESOLVED = 'resolved';
REJECTED = 'rejected';
constructor(fn) {
this.status = this.PENDING;
this.value = '';
this.resolveCallbacks = [];
this.rejectCallbacks = [];
try {
fn(this.resolve, this.reject);
} catch (error) {
this.reject(reject);
}
};
resolve(value) {
if (this.status === this.PENDING) {
this.value = value;
this.status = this.RESOLVED;
this.resolveCallbacks.forEach(fn => fn(this.value));
};
return this;
};
reject(err) {
if (this.status === this.PENDING) {
this.value = err;
this.status = this.REJECTED;
this.rejectCallbacks.forEach(fn => fn(this.value));
}
return this;
};
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled == 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected == 'function' ? onRejected : value => value;
// 收集
if (this.status === this.PENDING) {
this.resolveCallbacks.push(onFulfilled);
this.rejectCallbacks.push(onRejected);
}
// 触发后的处理
if (this.status === this.RESOLVED) {
onFulfilled(this.value);
}
if (this.status === this.REJECTED) {
onRejected(this.value);
}
return this;
};
catch(onRejected) {
onRejected = typeof onRejected == 'function' ? onRejected : value => value;
if (this.status === this.PENDING) {
this.rejectCallbacks.push(onRejected);
}
if (this.status === this.REJECTED) {
onRejected(this.value);
}
return this;
};
finally(fn) {
fn = typeof fn == 'function' ? fn : () => {};
if (this.status === this.PENDING) {
this.resolveCallbacks.push(fn);
this.rejectCallbacks.push(fn);
} else {
fn();
}
};
}
三、Promise.race基本实现‘
核心思路点总结:
- 异步执行每一个promise 只要其中一个执行完成那race就结束并拿到结果
- 如果中途有promise出错直接Promise.all结束
Promise.prototype.race = function(promises) {
return new Promise((resolve, reject) => {
for (let i = 0; i < promises.length; i ++) {
let _promise = promises[i];
if (_promise && _promise.then) {
_promise.then(resolve, reject)
} else {
reject(_promise)
}
}
})
}
四、 Promise.all基本实现
核心思路点总结:
- 需要记录每一个promise的结果和顺序
- 需要一个指针记录执行完成的promise数量
- 当指针记录数等于promise数量时候结束Promise.all方法并返回结果
- 如果中途有promise出错直接Promise.all结束
Promise.prototype.all = function(promises) {
let result = [];
let point = 0;
let proLen = promises.length;
return new Promise((resolve, reject) => {
for(let i = 0; i < proLen; i ++) {
Promise.resolve(promises[i]).then(res => {
result[i] = res;
point++;
if (point >= proLen) {
return resolve(result);
}
}, err => {
return reject(err);
})
}
})
}