export const sleep = (ms: number) =>
  new Promise((resolve) => setTimeout(resolve, ms));

/**
 * 在最大并发数MAX_REQUEST_NUM下，执行请求。
 * @param promiseArray
 * @param MAX_REQUEST_NUM
 */
export const executePromiseArray = async (
  promiseArray: (() => Promise<any>)[],
  MAX_REQUEST_NUM = 8
) => {
  const newPromiseFnArr = promiseArray.map((promiseFn, index) => {
    return {
      index,
      promiseFn,
      isLock: false,
    };
  });

  function execPromiseFnAndDoNext(
    promiseFnItem: typeof newPromiseFnArr[0] | undefined
  ) {
    if (promiseFnItem) {
      newPromiseFnArr[promiseFnItem.index].isLock = true;
      promiseFnItem.promiseFn().then(() => {
        const theFindedPromiseFnItem = newPromiseFnArr.find(
          (i) => i.isLock === false
        );
        if (theFindedPromiseFnItem) {
          execPromiseFnAndDoNext(theFindedPromiseFnItem);
        }
      });
    }
  }

  newPromiseFnArr.slice(0, MAX_REQUEST_NUM).forEach((promiseFnItem) => {
    execPromiseFnAndDoNext(promiseFnItem);
  });
};
