function promiseAll(iterable) {
const isIterable = subject =>
subject != null && typeof subject[Symbol.iterator] === 'function';
const validateIterable = subject => {
if (isIterable(subject)) return;
throw new TypeError(
`Cannot read property 'Symbol(Symbol.iterator)' of ${Object.prototype.toString.call(
subject
)}`
);
};
const isEmptyIterable = subject => {
for (let _ of subject) {
return false;
}
return true;
};
return new Promise((resolve, reject) => {
// 对输入进行检验
validateIterable(iterable);
let iterableSize = 0;
const values = [];
// 处理空输入 []
if (isEmptyIterable(iterable)) return resolve(values);
const add = (value, index) => {
values[index] = value;
if (values.filter(() => true).length === iterableSize) {
resolve(values);
}
};
for (let item of iterable) {
((entry, index) => {
Promise.resolve(entry).then(value => add(value, index), reject);
})(item, iterableSize++);
}
});
}
const P1 = () => {
return new Promise((resolve, reject) => {
console.log('-----P1 进来了呢');
setTimeout(() => {
console.log('P1--------');
resolve('P111111');
}, 500);
});
};
const P2 = () => {
return new Promise((resolve, reject) => {
console.log('-----P2 进来了呢');
setTimeout(() => {
console.log('P2--------');
resolve('P22222222');
}, 500);
});
};
promiseAll([P1(), P2()])
.then(responses => {
responses.forEach(res => {
console.log(res);
});
})
.catch(err => {
console.log('-=-=-', err);
});
console