方法一
const query = function query(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(time)
}, time)
})
}
let stack = [
() => {
return query(1000);
},
() => {
return query(2000);
},
() => {
return query(3000);
},
() => {
return query(4000);
},
]
const asyncPool = function asyncPool(stack, threadCount) {
if (!Array.isArray(stack)) throw new TypeError(`${stack} is not a Array`);
if (typeof threadCount == null) threadCount = 2;
if (typeof threadCount != 'number') throw new TypeError(`${threadCount} is not a number`);
let working = new Array(threadCount).fill(null),
index = 0,
values = [];
working = working.map(() => {
return new Promise((resolve, reject) => {
const next = async function next() {
if (index >= stack.length) {
resolve();
return;
}
try {
let result = await stack[index++]();
values[index-1] = result;
} catch (error) {
values[index-1] = null;
}
next();
}
next();
})
})
return Promise.all(working).then((res) => {
return values
});
}
asyncPool(stack, 2).then((res) => {
console.log(res)
})