列举面试常考的Promise静态方法
1.Promise.all
2.Promise.allSettled
3.Promise.race
4.Promise.resolve
5.Promise.finally
6.Promise.catch
没涉及到的可评论补充,我更新文章
所有(异步/非异步)任务执行完,必须所有都成功
Promise.prototype.myAll = (array) => {let result = []let index = 0// 返回promise为了链式调用 return new Promise((resolve, reject) => {// 归纳数据方法function addData(key, value) {result[key] = valueif (++index === array.length) {resolve(result)}}// 遍历数组参数执行异步任务for(let i = 0; i < array.length; i++){let current = array[i]if (current instanceof Promise) {// promise 对象current.then(value => addData(i, value), reason => reject(reason))} else {// 普通值addData(i, array[i])}}})
}
所有(异步/非异步)任务执行完,不管成功失败都输出,并且附带状态
Promise.prototype.myAllSettled = (array) => {let result = []let index = 0// 返回promise为了链式调用 return new Promise((resolve, reject) => {// 归纳数据方法function addData(key, status, value) {result[key] = {status, value}if (++index === array.length) {resolve(result)}}// 遍历数组参数执行异步任务for(let i = 0; i < array.length; i++){let current = array[i]if (current instanceof Promise) {// promise 对象current.then(value => {addData(i, 'fulfilled', value)}, reason => {addData(i, 'rejected', reason)})} else {// 普通值addData(i, 'fulfilled', array[i])}}})
}
输出(异步/非异步)任务执行最快的一个
Promise.prototype.myRace = (array) => {// 返回promise为了链式调用 return new Promise((resolve, reject) => {// 遍历数组参数执行异步任务for(let i = 0; i < array.length; i++){let current = array[i]if (current instanceof Promise) {// promise 对象current.then(value => resolve(value), reason => reject(reason))} else {// 普通值resolve(current)}}})
}
将给定的值转换为promise对象
Promise.prototype.myResolve = (value) => {if (value instanceof Promise) { return value;}return new Promise(reslove => reslove(value))
}
不管promise成功还是失败,finally方法都会被调用借用then方法拿到promise链式调用结果
finally(callback) {return this.then(value => {return Promise.resolve(callback()).then(() => value)}, reason => {return Promise.resolve(callback()).then(() => { throw reason })})
}
只需要借助then的失败回调
catch(failCallback){return this.then(undefined, failCallback)
}
基本覆盖常考点,大家需要可继续补充,求点一个赞!