0

I'm going through a promises tutorial and I can't wrap my head around how the parameter toss is assigned the value from function tossASix(). If anyone could take the time to explain it that would be greatly appreciated.

function dieToss() {
  return Math.floor(Math.random() * 6) + 1;  
}

function tossASix() {
  return new RSVP.Promise(function(fulfill, reject) {
    var n = Math.floor(Math.random() * 6) + 1;
    if (n === 6) {
      fulfill(n);
    } else {
      reject(n);
    }
  });
}

function logAndTossAgain(toss) {
  console.log("Tossed a " + toss + ", need to try again.");
  return tossASix();
}

function logSuccess(toss) {
  console.log("Yay, managed to toss a " + toss + ".");
}

function logFailure(toss) {
  console.log("Tossed a " + toss + ". Too bad, couldn't roll a six");
}

tossASix()
  .then(null, logAndTossAgain)   //Roll first time
  .then(null, logAndTossAgain)   //Roll second time
  .then(logSuccess, logFailure); //Roll third and last time
Rhys Edwards
  • 771
  • 2
  • 14
  • 32

2 Answers2

1

.then takes two parameters, both of which are actually single parameter functions. In the first two thens, your fulfill functions are both null, whereas the reject function is logAndTossAgain(toss). The Promise will call either the fulfillment function or rejection function based on the criteria within it (in this case whether the random result is 6 or not). So, the value of the random roll, n, is then passed to the logAndTossAgain function (if it wasn't a 6). And that's your value for the toss parameter.

ManoDestra
  • 6,325
  • 6
  • 26
  • 50
0

.then implicitly pass the argument.

As per the promise specification:

If onFulfilled is a function: it must be called after promise is fulfilled, with promise's value as its first argument.

In regards to passing arguments:

.then(foo)

is the same thing as

.then(function(val) { 
    foo(val) 
})

(in other regards, those two blocks of code are not equivalent)

Emil Oberg
  • 4,006
  • 18
  • 30