手写promise
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';
const resolvePromise = (promise2, x, resolve, reject) => {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
}
let called;
if ((typeof x === 'object' && x != null) || typeof x === 'function') {
try {
let then = x.then;
if (typeof then === 'function') {
then.call(x, y => {
if (called) return;
called = true;
resolvePromise(promise2, y, resolve, reject);
}, r => {
if (called) return;
called = true;
reject(r);
});
} else {
resolve(x);
}
} catch (e) {
if (called) return;
called = true;
reject(e)
}
} else {
resolve(x)
}
}
class Promise {
constructor(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks = [];
this.onRejectedCallbacks= [];
let resolve = (value) => {
if(value instanceof Promise){
return value.then(resolve,reject)
}
if(this.status === PENDING) {
this.status = FULFILLED;
this.value = value;
this.onResolvedCallbacks.forEach(fn=>fn());
}
}
let reject = (reason) => {
if(this.status === PENDING) {
this.status = REJECTED;
this.reason = reason;
this.onRejectedCallbacks.forEach(fn=>fn());
}
}
try {
executor(resolve,reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err };
let promise2 = new Promise((resolve, reject) => {
if (this.status === FULFILLED) {
setTimeout(() => {
try {
let x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e)
}
}, 0);
}
if (this.status === REJECTED) {
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e)
}
}, 0);
}
if (this.status === PENDING) {
this.onResolvedCallbacks.push(() => {
setTimeout(() => {
try {
let x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e)
}
}, 0);
});
this.onRejectedCallbacks.push(()=> {
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject)
} catch (e) {
reject(e)
}
}, 0);
});
}
});
return promise2;
}
catch(errCallback) {
return this.then(null,errCallback)
}
finally(callback) {
return this.then((value)=>{
return Promise.resolve(callback()).then(()=>value)
},(reason)=>{
return Promise.resolve(callback()).then(()=>{throw reason})
})
}
static resolve(data){
return new Promise((resolve,reject)=>{
resolve(data);
})
}
static reject(reason){
return new Promise((resolve,reject)=>{
reject(reason);
})
}
static all(values) {
if (!Array.isArray(values)) {
const type = typeof values;
return new TypeError(`TypeError: ${type} ${values} is not iterable`)
}
return new Promise((resolve, reject) => {
let resultArr = [];
let orderIndex = 0;
const processResultByKey = (value, index) => {
resultArr[index] = value;
if (++orderIndex === values.length) {
resolve(resultArr)
}
}
for (let i = 0; i < values.length; i++) {
let value = values[i];
if (value && typeof value.then === 'function') {
value.then((value) => {
processResultByKey(value, i);
}, reject);
} else {
processResultByKey(value, i);
}
}
});
}
static race(promises) {
return new Promise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
let val = promises[i];
if (val && typeof val.then === 'function') {
val.then(resolve, reject);
} else {
resolve(val)
}
}
});
}
}
Promise.defer = Promise.deferred = function () {
let dtd = {}
dtd.promise = new Promise((resolve, reject) => {
dtd.resolve = resolve;
dtd.reject = reject;
})
return dtd;
}
module.exports = Promise
参考资料
手写promise.all()
原理分析
- Promise.all:入参是一个 promise 集合;返回一个 Promise 实例;
- 所有 promise 的 resolve 回调结果都会被放入到一个数组;
- 所有 promise 都执行成功且调用 resolve 后,返回的 Promise 才调用 resolve 成功,并返回全部执行结果;
- 任何一个 promise 执行调用 reject 或抛出错误,返回的 Promise 就会调用 reject 失败,并返回第一个失败结果;
代码实现
// Promise.all 处理 promise 集合
static all (promises) {
// Promise.all 返回一个 Promise
return new Promise((resolve, reject)=>{
// 创建集合 result,用于顺序存放 Promise 执行结果
// 全部执行成功,调用 resolve(result),返回全部执行结果
let result = [];
// 遍历执行 每一个 promises
for(let i = 0;i < promises.length; i++){
let p = promises[i];
// promise 类型,promise.then
if(p && typeof p.then ==='function'){
p.then((data)=>{
// todo 执行结果放入 result
}, reject) // 任何一个 promise 失败,直接失败
// 非 promise 类型
}else{
// todo
}
}
})
}
还有以下关键问题需要解决:
1:如何按照执行顺序存放异步操作的返回结果?
按照异步操作执行顺序,放入 result 数字下标的对应位置;
2:如何判定集合内的 promise 已经全部执行完成?
如果使用 result.length,后面异步操作如果先返回放入数组,判断 length 就不准了;
可以使用计数器,每次 promise 成功 index++,直至index === promises.length;
最终代码实现如下:
static all (promises) {
if (!Array.isArray(promises)) {
const type = typeof values;
return new TypeError(`TypeError: ${type} ${values} is not iterable`)
}
return new Promise((resolve, reject)=>{
let result = [];
let times = 0;
// 将成功结果放入数组中对应的位置
const processSuccess = (index, val)=>{
result[index] = val;
if(++times === promises.length){
resolve(result); // 全部执行成功,返回 result
}
}
// 遍历处理集合中的每一个 promise
for(let i = 0;i < promises.length; i++){
let p = promises[i];
if(p && typeof p.then ==='function'){
// 调用这个p的 then 方法
p.then((data)=>{
// 按照执行顺序存放执行结果
processSuccess(i, data)
}, reject);
}else{
// 普通值,直接按照执行顺序放入数组对应位置
processSuccess(i, p)
}
}
})
}