WriterState WriterState - 1 month ago 9
Javascript Question

Promise resolve will not fire. Easy script

I'm wondering why this will not log out the resolve .then method. The idea is to log out every failure, then as soon as the values match, log out the "Winner Winner" that is in the .then method.



var winner = 5;
var ticket = 0;
var roll = function() {
ticket = Math.round(Math.random() * 10);
}
var play = function() {
roll();
return new Promise(function(resolve, reject) {
if (ticket === winner) {
resolve();
} else {
console.log("Sorry Try Again");
play();
}
});

}


play().then(function() {
console.log("Winner Winner!")
});




Answer

You're only logging the winner when the first play() succeeds, not the recursive ones. Add a .then() to the inner call.

var winner = 5;
var ticket = 0;
var roll = function() {
  ticket = Math.round(Math.random() * 10);
}
var play = function() {
  roll();
  return new Promise(function(resolve, reject) {
    if (ticket === winner) {
      resolve();
    } else {
      console.log("Sorry Try Again");
      play().then(function() {
        console.log("Winner Winner");
      });
    }
  });

}


play().then(function() {
  console.log("Winner Winner!")
});

If you don't want to repeat that code in both places, define a function that does it.

var winner = 5;
var ticket = 0;
var roll = function() {
  ticket = Math.round(Math.random() * 10);
}
var play = function() {
  roll();
  return new Promise(function(resolve, reject) {
    if (ticket === winner) {
      resolve();
    } else {
      console.log("Sorry Try Again");
      playtest();
    }
  });

}

function playtest() {
  play().then(function() {
    console.log("Winner Winner!")
  });
}

playtest();

Comments