参数的值是如何分配给这个函数的?

How is the parameter's value assigned to this function?

我正在阅读 promises 教程,但我无法理解参数 toss 是如何从 function tossASix() 中赋值的。如果有人能花时间解释一下,将不胜感激。

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

.then 隐式传递参数。

根据 promise specification:

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

关于传递参数:

.then(foo)

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

(在其他方面,这两段代码不等价)

.then 有两个参数,其实都是单参数函数。在前两个 then 中,你的 fulfill 函数都是 null,而 reject 函数是 logAndTossAgain(toss)。 Promise 将根据其中的条件调用 fulfillment 函数或 rejection 函数(在本例中随机结果是否为 6)。因此,随机掷骰的值 n 将传递给 logAndTossAgain 函数(如果它不是 6)。这就是你的 toss 参数值。