arrays - typescript:异步函数作为另一个函数的参数被执行而不是挂起
问题描述
我正在尝试创建通用函数来平衡并行运行的 Promise 数量。主要主题是控制 google API 调用以避免达到 google 定义的某些配额。
我正在创建一个值数组。然后我遍历这个数组,并创建一个 Promise 数组。每个 Promise 都以值作为参数调用一个函数。最后,我正在为每块 X 待处理的 Promise 运行一个 Promise.all
不幸的是,在创建“待定”承诺数组时,作为参数传递的函数被执行。因此,通过 Promise.all 控制并发执行是没有用的。
下面是代码。Rgds
以函数作为参数创建承诺数组的函数
const createArrayOfFunctionPromise = <T>(
arrayVal: T[],
functionToExecute: (...args: any[]) => any
): Array<Promise<T[]>> => {
const resu: Array<Promise<T[]>> = [];
arrayVal.forEach((val: T, index: number) => {
resu.push(functionToExecute(val, index));
});
return resu;
};
按块执行承诺数组的函数
const executeArrayOfFunctionPromiseByChunk = async <T>(
arrValue: T[],
functionToExecute: (...args: any[]) => any,
chunk?: number
): Promise<T[]> => {
const arrP: Array<Promise<T[]>> = createArrayOfFunctionPromise<T>(
arrValue,
functionToExecute
);
let data: T[][] = [];
if (chunk) {
if (chunk > 0) {
let tmpArr: Array<Promise<T[]>> = [];
for (let i: number = 0; i < arrP.length; i += 1) {
tmpArr.push(arrP[i]);
if (i % chunk === 0 || i === arrP.length - 1) {
const d = await Promise.all(tmpArr);
data.push(d.flat(1));
tmpArr = [];
}
}
} else {
return [];
}
} else {
data = await Promise.all(arrP);
}
// console.log(data);
return data.flat(1);
};
要执行的函数示例
const dummyFunction = async (val: string, index: number): Promise<string[]> => {
let resu: string[] = [];
resu = [...resu, await dummyPromise<string>(`${val} appel 1`, index)];
resu = [...resu, await dummyPromise<string>(`${val} appel 2`, index + 0.5)];
resu = [...resu, await dummyPromise<string>(`${val} appel 3`, index + 1.2)];
resu = [...resu, await dummyPromise<string>(`${val} appel 4`, index + 1.7)];
resu = [...resu, await dummyPromise<string>(`${val} appel 5`, index + 0.7)];
return resu;
};
const dummyPromise = async <T>(param: T, index: number): Promise<T> => {
return new Promise(resolve => {
setTimeout(() => resolve(param), 3 * index * 1000);
console.log("dans dummypro", 3 * index * 1000);
});
};
要运行的测试程序 - 应该执行函数 dummyFunction 2 by 2 (chunk=2) 同时循环 3 个元素的数组
const test = async (array: string[]): Promise<string[]> => {
const result: string[] = await executeArrayOfFunctionPromiseByChunk<string>(
array,
dummyFunction,
2
);
return result;
};
test(["a", "b", "c"]).then((result: string[]) => {
console.log(result.flat(1));
});
解决方案
推荐阅读
- r - 具有多元回归和面板数据的 Rollregres
- gooddata - 指标中的条件语句在 Gooddata 报告中无法正常工作
- kotlin - Jacoco Kotlin 数据类过滤 getter 和 setter?
- sql-server - INNER JOIN 优于 CROSS APPLY 的好处
- amazon-web-services - 带有 multer-3S 的 AWS lambda 上传不受支持的图像文件。但本地服务器上传正确
- php - 如果用户输入[复选框]和文本区域为空,PHP 将 CSV 列留空
- node.js - 将字符串数组从节点 js 获取到 ejs
- html - 为什么无论我尝试什么按钮都不会向上移动?
- tensorflow - 在 Flask 中导入多个自定义 tensor2tensor 问题
- css - 如果 mat-form-field 在组件中,表单布局会中断