Joey / src /utils /common.ts
yuanjiajun
feat: 单图
139dfb9
raw
history blame contribute delete
917 Bytes
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;
}