javascript (promise) puzzle

How would you write the following code if you had to use Promises?

The idea is that a "private" method p1 makes a call to a function that does something asynchronous and then, when the result of the asynchronous call is ready, the control is passed to the "private" method p2. Just like p1, p2 makes a call to a function that executes some asynchronous stuff and then, the control is passed back to p1. In this example, this keeps going forever.

As you can imagine I have boiled down my code to a more theoretical scenario to make it short. In practice, p1 and p2 are doing two different things and based on some conditions in p1 and p2 the program execution do stop.

mySimpleRunner = (function () {

  var service = {}; 

  var async = function (cb) {
    var n = Math.floor(Math.random() * 1000);
    setTimeout(function () {
      cb(n);
    }, n); 
  }

  var p1 = function (r) {
    async(p2);
    console.log("1:", r || "first call");
  };  

  var p2 = function (r) {
    async(p1);
    console.log("2:", r); 
  };  

  service.run = function () {
    p1();
  }

  return service;

})();

mySimpleRunner.run();

I have tried many possible ways to do the same with Promises, where instead of passing the function cb to async, async is a Promise that resolves when the timer is done. But I haven't figured out how to do this properly.

If you have sometime and you want to give it a try, I would really appreciate.

Answers


Not a whole lot of difference really. The only thing is that you pass the callback to then instead if async:

function async() {
    return new Promise(function (resolve) {
        var n = Math.floor(Math.random() * 1000);
        setTimeout(resolve.bind(null, n), n);
    });
}

function p1(r) {
    async().then(p2);
    console.log(r);
}

function p2(r) {
    async().then(p1);
    console.log(r);
}

Need Your Help

issue with "this" keyword in plugin and jQuery animate()

javascript jquery plugins jquery-animate this

I am trying my luck at authoring a plugin with jQuery but I am having a few issues. So I want to make this plugin where I take some divs and add a read more or read less link after these divs.