我有一个大型阵列,它被分成更小的块。然后我对每个块进行异步调用:
myFunc(arrObjs: any[], chunkSize: number): Promise<any> {
let result = Promise.resolve(); // To start the chain
while(arrObjs.length) {
// Extracting array chunk
let chunk = arrObjs.splice(0, chunkSize);
// Building the chain
result = result.then(() => {
return someAsynFunc(
chunk
);
});
}
return result;
}
高于我的解决方案。我需要按顺序运行异步函数(系列承诺),所以我建立了一系列的承诺。
有没有更好的方法来做到这一点?
答案 0 :(得分:6)
是的,您可以使用reduce
模式:
function myFunc(arrObjs: any[], chunkSize: number): Promise<any> {
const chunks : any[] = [];
while (arrObjs.length) {
chunks.push(arrObjs.splice(0, chunkSize));
}
return chunks.reduce((p : Promise<any>, chunk : any[]) => {
return p.then(() => someAsyncFunc(chunk));
}, Promise.resolve());
}
(我认为我的那些类型注释是正确的;如果没有,希望你可以阅读它...)
请注意,我保留了原来的行为,实际上是从arrObjs
数组中删除数据,但通常我不主张更改从调用方传递的对象。
以下是一个例子:
function myFunc(arrObjs, chunkSize) {
const chunks = [];
while (arrObjs.length) {
chunks.push(arrObjs.splice(0, chunkSize));
}
return chunks.reduce((p, chunk) => {
return p.then(() => someAsyncFunc(chunk));
}, Promise.resolve());
}
function someAsyncFunc(chunk) {
console.log("Start handling", JSON.stringify(chunk));
return new Promise(resolve => {
setTimeout(() => {
console.log("Done handling", JSON.stringify(chunk));
resolve();
}, 800);
});
}
const array = [0, 1, 2, 4, 5, 6, 7, 8, 9];
myFunc(array, 3).then(() => {
console.log("Done");
});
另请注意,上面会删除处理它们的数组中的所有块。如果你想这样做作为它们被处理(它与使用该数组的任何其他东西创建交叉对话,可以添加/删除/等),你可以做同样的事情,只是没有reduce
:
// Cross-talky version
function myFunc(arrObjs : any[], chunkSize : number) : Promise<any> {
return new Promise<any>(function processChunk(resolve : function) {
const chunk : any[] = arrObjs.splice(0, chunkSize);
if (chunk.length == 0) {
resolve();
} else {
someAsyncFunc(chunk).then(() => processChunk(resolve));
}
});
}
// Cross-talky version
function myFunc(arrObjs, chunkSize) {
return new Promise(function processChunk(resolve) {
const chunk = arrObjs.splice(0, chunkSize);
if (chunk.length == 0) {
resolve();
} else {
someAsyncFunc(chunk).then(() => processChunk(resolve));
}
});
}
function someAsyncFunc(chunk) {
console.log("Start handling", JSON.stringify(chunk));
return new Promise(resolve => {
setTimeout(() => {
console.log("Done handling", JSON.stringify(chunk));
resolve();
}, 800);
});
}
const array = [0, 1, 2, 4, 5, 6, 7, 8, 9];
myFunc(array, 3).then(() => {
console.log("Done");
});
setTimeout(() => {
array.splice(2, 0, 'cross', 'talk');
}, 1000);