Javascript承诺:传递的参数可以超出范围吗?

时间:2017-01-17 13:58:35

标签: javascript promise

我正在关注promises,here的javascript教程,特别是这段代码(模拟死亡):

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

function tossASix() {
  return new 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

我认为它很清楚它在做什么,但是,作为测试,我改变了最后几行而不是

tossASix()
  .then(logSuccess, logAndTossAgain)   //Roll first time
  .then(logSuccess, logAndTossAgain)   //Roll second time
  .then(logSuccess, logFailure); //Roll third and last time

如果我理解正确的承诺(请在这里承担,因为我仍然试图绕过他们)我会想到当我在第一次投掷时获得6时,输出将是< / p>

Yay, managed to toss a 6.
Yay, managed to toss a 6.
Yay, managed to toss a 6.

但实际上我得到的是

Yay, managed to toss a 6.
Yay, managed to toss a undefined.
Yay, managed to toss a undefined.

为什么? 这是否意味着在第一次调用logSuccess(也就是说实现)之后,参数n超出了范围?如果是这样的话?它是否与承诺只履行一次这一事实有关?

2 个答案:

答案 0 :(得分:1)

then接受两个参数:第一个是resolve回调,第二个是reject回调,并返回一个新的Promise

由于您在6的第一次通话时收到tossASix,因此您不会致电logAndTossAgain,因为您将其作为reject回调传递,并继续记录undefined 1}}值,因为作为logSuccess提供的函数resolve不会返回任何内容。

您可以阅读有关承诺链接的更多信息here

答案 1 :(得分:0)

1: tossASix()
2:   .then(logSuccess, logAndTossAgain)   //Roll first time
3:   .then(logSuccess, logAndTossAgain)   //Roll second time
4:   .then(logSuccess, logFailure); //Roll third and last time

tossASix解析/ fullfil时,第2行的logSuccess使用参数6调用,并且返回(未定义)将作为参数传递到第3行的logSuccess并且在第4行再次发生。

如果你想看到像这样的回归

Yay, managed to toss a 6.
Yay, managed to toss a 6.
Yay, managed to toss a 6.

您需要在n函数返回logSuccess,以便将值传递到下一个函数。