Guest User

Untitled

a guest
Apr 25th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. /**
  2. * Example of an async function which returns some value
  3. */
  4. function doSomething() {
  5. return new Promise((resolve, reject) => {
  6. window.setTimeout(function () {
  7. resolve(Math.random() > 0.8);
  8. }, 1000);
  9. });
  10. }
  11.  
  12. /**
  13. * Checks whether a condition applies, in order to tell waitUntil to proceed
  14. * @param {object} data - The response from the business function above
  15. */
  16. function evaluate(data) {
  17. return data === true;
  18. }
  19.  
  20. /**
  21. * Waits for a condition to be truthy and proceed
  22. */
  23. async function waitUntil(extract, evaluate, max) {
  24. let data;
  25. let truthy;
  26. let counter = 0;
  27.  
  28. while ((!max||counter < max) && !truthy) {
  29. data = await extract();
  30. truthy = evaluate(data);
  31. counter++
  32. };
  33.  
  34. return data;
  35. }
  36.  
  37. // how to use:
  38. waitUntil(doSomething, evaluate)
  39. .then(isTrue => console.log(isTrue));
  40.  
  41. // how to use - try 3 times maximum:
  42. waitUntil(doSomething, evaluate, 3)
  43. .then(isTrue => console.log(isTrue));
Add Comment
Please, Sign In to add comment