File size: 917 Bytes
c84f41e
 
 
 
 
 
 
bf7d5e4
1750670
9222dec
 
 
 
 
b118dd1
c026213
9222dec
 
b3d0047
9222dec
bf7d5e4
04caba1
ec10306
 
 
 
 
 
7262592
ec10306
7262592
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import util from 'util';
const setTimeoutPromise = util.promisify(setTimeout);

export async function delay(time: number) {
  await setTimeoutPromise(time);
  console.log(`延迟${time}毫秒后执行`);
}

export async function retryAsync(func: () => Promise<any>, x = 3, timeout = 10 * 1000) {
  let attempts = 0;
  while (attempts < x) {
    try {
      return await func();
    } catch (error) {
      console.log(`第${attempts + 1}次尝试失败:${error}`);
      await delay(timeout);
      attempts++;
    }
  }
  throw new Error(`Async function failed after ${x} attempts.`);
}

export function getRandomUniqueElements(arr: any[], x: number): any[] {
  const result: any[] = [];
  const copyArr = arr.slice();
  while (result.length < x && copyArr.length > 0) {
    const randomIndex = Math.floor(Math.random() * copyArr.length);
    result.push(copyArr.splice(randomIndex, 1)[0]);
  }
  return result;
}