Avatar for DavidV

DavidV

Member since Aug 2020 • Last active Aug 2020
  • 1 conversations
  • 1 comments

Most recent activity

    • 3 comments
    • 278 views
  • in Tutorials
    Avatar for DavidV

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

    // Simple promise
    function Kvp(key, value) {
      return new Promise(function(resolve, reject) {
        console.log(key, value);
        resolve();
      });
    }
    
    // Promise which runs every value second
    function RunOn(value) {
      return new Promise(function(resolve, reject) {
        setInterval(function() {
          console.log(new Date().toISOString().substring(11, 19));
          resolve();
        }, value * 1000);
      });
    }
    
    // Promise which runs once after value seconds
    function RunOnce(value) {
      return new Promise(function(resolve, reject) {
        var runOnce = setInterval(() => {
          console.log("RunOnce", value);
          clearInterval(runOnce); //stop function
          resolve();
        }, value * 1000);
      });
    }
    
    RunOn(1);
    Kvp('A', 1).then(function() {
      Kvp('B', 2);
    });
    RunOnce(5).then(() => {
      Kvp("C", 5);
    }).then(() => {
      Kvp('fin', 12);
    });
    
Actions