all
1 2 3 4 5 6 7 8 9 10 11 12 13
| Promise.MyAll = function (promises) { let arr = [], count = 0 return new Promise((resolve, reject) => { promises.forEach((item, i) => { Promise.resolve(item).then(res => { arr[i] = res count += 1 if (count === promises.length) resolve(arr) }, reject) }) }) }
|
race
1 2 3 4 5 6 7 8
| Promise.MyRace = function (promises) { return new Promise((resolve, reject) => { for (const item of promises) { Promise.resolve(item).then(resolve, reject) } }) }
|
any
1 2 3 4 5 6 7 8 9 10 11 12 13
| Promise.MyAny = function (promises) { let arr = [], count = 0 return new Promise((resolve, reject) => { promises.forEach((item, i) => { Promise.resolve(item).then(resolve, err => { arr[i] = { status: 'rejected', val: err } count += 1 if (count === promises.length) reject(new Error('没有promise成功')) }) }) }) }
|
allSettled
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| Promise.MyAllSettled = function (promises) { let arr = [], count = 0 return new Promise((resolve, reject) => { promises.forEach((item, i) => { Promise.resolve(item).then(res => { arr[i] = { status: 'fulfilled', val: res } count += 1 if (count === promises.length) resolve(arr) }, (err) => { arr[i] = { status: 'rejected', val: err } count += 1 if (count === promises.length) resolve(arr) }) }) }) }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| Promise.MyAllSettled = function (promises) { let arr = [], count = 0 return new Promise((resolve, reject) => { const processResult = (res, index, status) => { arr[index] = { status: status, val: res } count += 1 if (count === promises.length) resolve(arr) }
promises.forEach((item, i) => { Promise.resolve(item).then(res => { processResult(res, i, 'fulfilled') }, err => { processResult(err, i, 'rejected') }) }) }) }
|
reject
1 2 3 4 5
| Promise.myReject = function (value) { return new Promise((_, reject) => { reject(value) }) }
|
ref
https://juejin.cn/post/7069805387490263047
https://juejin.cn/post/7038371452084551694