async.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { __awaiter } from "tslib";
  2. export function asyncWhile(checker, callback) {
  3. return __awaiter(this, void 0, void 0, function* () {
  4. let index = 0;
  5. const newCallback = () => __awaiter(this, void 0, void 0, function* () {
  6. const checkRes = yield checker(index);
  7. if (checkRes) {
  8. yield callback(index);
  9. index++;
  10. yield newCallback();
  11. }
  12. });
  13. return yield newCallback();
  14. });
  15. }
  16. export function asyncForEach(array, callback) {
  17. return __awaiter(this, void 0, void 0, function* () {
  18. let index = 0;
  19. const newCallback = () => __awaiter(this, void 0, void 0, function* () {
  20. const item = array[index];
  21. const res = yield callback(item, index);
  22. if (index < array.length - 1 && res !== false) {
  23. index++;
  24. yield newCallback();
  25. }
  26. });
  27. return yield newCallback();
  28. });
  29. }
  30. export function nextTick(time = 0) {
  31. return new Promise((resolve) => {
  32. setTimeout(() => {
  33. resolve(true);
  34. }, time);
  35. });
  36. }
  37. export function objectForEach(obj, callback) {
  38. const keys = Reflect.ownKeys(obj);
  39. keys.forEach((key) => {
  40. callback(Reflect.get(obj, key), key);
  41. });
  42. }
  43. export function asyncObjectForEach(obj, callback) {
  44. return __awaiter(this, void 0, void 0, function* () {
  45. const keys = Reflect.ownKeys(obj);
  46. let index = 0;
  47. const newCallback = () => __awaiter(this, void 0, void 0, function* () {
  48. const key = keys[index];
  49. const res = yield callback(Reflect.get(obj, key), key);
  50. if (index < keys.length - 1 && res !== false) {
  51. index++;
  52. yield newCallback();
  53. }
  54. });
  55. return yield newCallback();
  56. });
  57. }