Promise finally
这是一个 promise 实例原型链上的办法
Promise.prototype.finally = function(func) {return this.then((value) => {Promise.resolve(func()).then(() => value)
},
(reason) => {Promise.resolve(func()).then(() => {throw reason})
})
}
Promise.All
if (!arr[Symbol.iterator]) throw 'param is not iterable';
const promiseArr = Array.from(arr).map(a => {if (a instanceof Promise) {return a;} else {return Promise.resolve(a);
}
})
if (promiseArr.length === 0) return Promise.resolve([]);
return new Promise((resolve, reject) => {let result = [];
let count = promiseArr.length;
promiseArr.forEach((p, i) => {
p.then((res => {result[i] = res;
count--;
if (count === 0) resolve(result);
}, (reason) => reject(reason)))
})
})
留神点
- 入参必须是可迭代的
- 参数转化为数组,且所有的项必须转化为 Promise
- 返回值永远是一个 Promise
- 入参如果长度是 0 那间接返回 Promise.resolve([]) 不然 Promise.all([])返回的 promise 永远处于 pending 状态
Promise.race
const PromiseRace = (arr) => {if (arr[Symbol.iterator] === undefined) return Promise.reject('param is not iterator')
const promiseArr = Array.from(arr).map(a => {if (a instanceof Promise) {return a;} else {return Promise.resolve(a);
}
})
return new Promise((resolve, reject) => {promiseArr.forEach((p, i) => {
p.then((res => {resolve(res);
}, (reason) => reject(reason)))
})
})
}
留神 Promise.race([])返回的应该是一个 pending 状态的 promise
Promise.any
const PromiseAny = (arr) => {if (arr[Symbol.iterator] === undefined) return Promise.reject('param is not iterator')
const promiseArr = Array.from(arr).map(a => {if (a instanceof Promise) {return a;} else {return Promise.resolve(a);
}
})
if (promiseArr.length === 0) return Promise.reject(new AggregateError([],'All promises were rejected'))
return new Promise((resolve, reject) => {const errors = [];
const count = promiseArr.length;
promiseArr.forEach((p, i) => {
p.then((res => {resolve(res);
}, (reason) => {errors[i] = reason;
count--;
if (count === 0) {reject(new AggregateError(errors,'All promises were rejected'))
}
}))
})
})
}
留神
- Promise.any 返回的谬误肯定是 AggregateError 类型的
Promise.allSettled
const PromiseAllSettled = (arr) => {if (arr[Symbol.iterator] === undefined) return Promise.reject('param is not iterator')
const promiseArr = Array.from(arr).map(a => {if (a instanceof Promise) {return a;} else {return Promise.resolve(a);
}
})
if (promiseArr.length === 0) return Promise.resolve([])
return new Promise((resolve, reject) => {const result = [];
const count = promiseArr.length;
promiseArr.forEach((p, i) => {
p.then((res => {result[i] = {status: 'fulfilled', value: res};
count--;
if (count === 0) {resolve(result)
}
}, (reason) => {result[i] = {status: 'rejected', reason: reason};
count--;
if (count === 0) {resolve(result)
}
}))
})
})
}
返回内容的格局肯定是 {status: ‘fulfilled’, value: res} 或者{status: ‘rejected’, reason: reason}