async.ts 916 B

123456789101112131415161718192021222324252627282930313233343536373839
  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. }