utilities.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. const log = require("./logger");
  3. /**
  4. * Creates delays in time. Ideal for gaurenteeing time between executions
  5. * between {Promise} resolve handlers.
  6. * @param time in milliseconds
  7. * @returns {Promise}
  8. */
  9. function delay(time) {
  10. return new Promise((resolve) => {
  11. log.info("Delaying for %d ms", time);
  12. setTimeout(() => resolve(time), time);
  13. });
  14. }
  15. /**
  16. * Repeats a promise until a condition is met, or `maxAttempts` have occurred
  17. * @param callback This is a function that should return the promise to repeat
  18. * @param checkFn A function that will run on each go, truthy values will stop the loop
  19. * @param maxAttempts [OPTIONAL] Number of times this should loop.
  20. * @returns {Promise}
  21. */
  22. function retryPromiseUntil(callback, checkFn, maxAttempts) {
  23. if (!callback.hasOwnProperty("attemptCount")) {
  24. callback.attemptCount = 0;
  25. }
  26. let result = checkFn();
  27. log.debug("Retrying promise...");
  28. if (result) {
  29. log.info("Check function returned", result);
  30. return result;
  31. }
  32. callback.attemptCount++;
  33. log.debug("Performing attempt", callback.attemptCount);
  34. if (maxAttempts && callback.attemptCount > maxAttempts) {
  35. log.warn("Max attempts reached exiting");
  36. return;
  37. }
  38. // Recursively return the promise
  39. return Promise.resolve()
  40. .then(() => callback())
  41. .then(() => retryPromiseUntil(callback, checkFn, maxAttempts));
  42. }
  43. /**
  44. * There is probably a better way to do this. This returns a synchronized thenable chain.
  45. */
  46. function promiseChain(promiseFunctions) {
  47. log.debug("Chaining %d promises", promiseFunctions.length);
  48. return promiseFunctions.reduce((prev, current, index) => {
  49. log.debug("Chaining promise #%d", index);
  50. // Lazily return the promise
  51. return prev.then(() => current());
  52. }, Promise.resolve());
  53. }
  54. module.exports = {
  55. delay: delay,
  56. retryPromiseUntil: retryPromiseUntil,
  57. promiseChain: promiseChain
  58. };