首页 > 解决方案 > 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));
  });

标签: arraystypescriptparallel-processingpromise

解决方案


推荐阅读