Simple Promise Example

Posted on
  • This is a super simple example of using promises to order execution of functions asyncronously.

    1. // Simple promise
    2. function Kvp(key, value) {
    3. return new Promise(function(resolve, reject) {
    4. console.log(key, value);
    5. resolve();
    6. });
    7. }
    8. // Promise which runs every value second
    9. function RunOn(value) {
    10. return new Promise(function(resolve, reject) {
    11. setInterval(function() {
    12. console.log(new Date().toISOString().substring(11, 19));
    13. resolve();
    14. }, value * 1000);
    15. });
    16. }
    17. // Promise which runs once after value seconds
    18. function RunOnce(value) {
    19. return new Promise(function(resolve, reject) {
    20. var runOnce = setInterval(() => {
    21. console.log("RunOnce", value);
    22. clearInterval(runOnce); //stop function
    23. resolve();
    24. }, value * 1000);
    25. });
    26. }
    27. RunOn(1);
    28. Kvp('A', 1).then(function() {
    29. Kvp('B', 2);
    30. });
    31. RunOnce(5).then(() => {
    32. Kvp("C", 5);
    33. }).then(() => {
    34. Kvp('fin', 12);
    35. });
  • Thanks - looks great!

  • @DavidV, I'd like you to be a bit more explanatory about what you intend to convey with your example(s). What is the console output?

    On related note, what is your reasoning to use setInterval() rather than setTimeout() in RunOnce()?

    On an unrelated note - since JavaScript is object-oriented and related practice is to use Upper/lower case to distinguish Class/Prototype 'things' from method/function/members/properties 'things' - what is the reasoning to use Uppercase identifiers for the functions?

    Doing an analysis of what is effectively going on, I see line 34 as the only Promise-worthy item. May be I look at the example(s) way too narrow minded, and you have a grander vision why to use Promises even though no asynchronous things happen (except - as already mentioned - in line 34). To me, it almost feels as: Why simple, if complicated/confusing works too?

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
    • $ Donate
About

Simple Promise Example

Posted by Avatar for DavidV @DavidV

Actions