示例

/**
 * 并发请求并返回结果
 * @param defers
 * @param options
 * @returns
 */
export const pmap = async <T>(
  tasks: Array<() => Promise<T>>,
  options: POptionType,
): Promise<T[]> => {
  // 并发量
  const concurrency = _.get(options, "concurrency", tasks.length);
  // 间隔
  const interval = _.get(options, "interval", 0);
 
  let result: T[] = [];
  const chunks = _.chunk(tasks, concurrency);
 
  for (const chunk of chunks) {
    const res = await Promise.all(chunk.map((t) => t()));
    result = result.concat(res);
    await delay(interval);
  }
 
  return result;
};
 
export const delay = (ms: number) =>
new Promise((resolve) => setTimeout(() => resolve(true), ms));