实现 Promises/A+ 规范
手写Promise.all
参数:必须具有iterator接口,如数组
返回:返回的每个成员都是新的promise实例(并传给新实例的回调方法)。
若所有成员的状态都变为fulfilled,则返回的promise实例状态为fulfilled,且入参每个成员的返回值*依次组成数组传给promise实例的回调函数;
若存在一个成员的状态变为rejected,则返回的promise实例状态为rejected,且rejected状态的成员的返回值传给promise实例的回调函数
- 判断入参,是否具有iterator接口
- 判断入参,是否为空,空返回fulfilled状态
- 需考虑fulfilled状态时结果的顺序(注意不能直接push,改为arr[i])
- 使用计数器
const isIterator = (val) => val !== null && val !== undefined && typeof val[Symbol.iterator] === 'function';
const isEmptyIterator = (val) => isIterator(val) && val[Symbol.iterator]().next().done;
Promise.newAll = function (promises) {
if (!isIterator(promises)) {
throw Error(`TypeError: number ${promises} is not iterable`);
}
return new Promise((resolve, reject) => {
if (isEmptyIterator(promises)) return resolve([]);
const length = promises.length;
const ans = [];
let count = 0;
promises.forEach((promise, i) => {
Promise.resolve(promise)
.then((res) => {
ans[i] = res;
count++;
if (count === length) {
resolve(ans);
}
})
.catch(reject);
});
});
};