async.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. export async function asyncWhile(
  2. checker: (index: number) => boolean | Promise<boolean>,
  3. callback: (index: number) => void | Promise<void>
  4. ) {
  5. let index = 0;
  6. const newCallback = async () => {
  7. const checkRes = await checker(index);
  8. if (checkRes) {
  9. await callback(index);
  10. index++;
  11. await newCallback();
  12. }
  13. };
  14. return await newCallback();
  15. }
  16. export async function asyncForEach<T = any>(
  17. array: T[],
  18. callback: (item: T, index: number) => boolean | Promise<boolean>
  19. ) {
  20. let index = 0;
  21. const newCallback = async () => {
  22. const item = array[index];
  23. const res = await callback(item, index);
  24. if (index < array.length - 1 && res !== false) {
  25. index++;
  26. await newCallback();
  27. }
  28. };
  29. return await newCallback();
  30. }
  31. export function nextTick(time = 0) {
  32. return new Promise((resolve) => {
  33. setTimeout(() => {
  34. resolve(true);
  35. }, time);
  36. });
  37. }
  38. export function objectForEach<O extends Record<PropertyKey, unknown>>(
  39. obj: O,
  40. callback: (value: O[keyof O], key: PropertyKey) => void
  41. ) {
  42. const keys = Reflect.ownKeys(obj);
  43. keys.forEach((key) => {
  44. callback(Reflect.get(obj, key), key);
  45. });
  46. }
  47. export async function asyncObjectForEach<
  48. O extends Record<PropertyKey, unknown>
  49. >(
  50. obj: O,
  51. callback: (value: O[keyof O], key: PropertyKey) => boolean | Promise<boolean>
  52. ) {
  53. const keys = Reflect.ownKeys(obj);
  54. let index = 0;
  55. const newCallback = async () => {
  56. const key = keys[index];
  57. const res = await callback(Reflect.get(obj, key), key);
  58. if (index < keys.length - 1 && res !== false) {
  59. index++;
  60. await newCallback();
  61. }
  62. };
  63. return await newCallback();
  64. }