1
\$\begingroup\$

Inside a function I'm calling playgame service. Once I've obtained the needed data (gameBeingPlayed), I need to show a 3..2..1 counter and then start a game.

chooseGameService.playGame(gameDefinitionID)
 .then(function () {
 vm.container.gameBeingPlayed = chooseGameService.gameBeingPlayed;
 showGame();
 counter(3); 
 });
 function counter(count) {
 vm.container.counterVisible = true;
 var countDownFrom = count;
 var timer = setInterval(function() { handleTimer(count); }, 1000);
 function handleTimer() {
 if(count === 0) {
 clearInterval(timer);
 //
 initGame();
 vm.container.counterVisible = false;
 } else {
 $('#gameCount').text(count);
 count--;
 }
 } 
 }

The things that bothers me is that I had to move the next two lines from the service (promise) callback to the counter in order to execute the code synchronously.

initGame();
vm.container.counterVisible = false;

It works, but it seems semantically wrong for me that initGame() and visibility change is inside the counter function instead of inside the callback of the service (which is inside the controller).

Is there any way I could keep these lines inside the .then() of the controller instead of inside the counter function?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Mar 9, 2016 at 14:12
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

I'd make the counter function return a promise. If you understand promises, I think this example will be enough. If not, please ask and I'll clarify.

function counter(count) {
 var deferred = Promise.defer();
 var countDownFrom = count;
 var timer = setInterval(function() { handleTimer(countDownFrom); }, 1000);
 function handleTimer(count) {
 if (count === 0) {
 clearInterval(timer);
 deferred.resolve();
 } else {
 console.log(count);
 countDownFrom--;
 }
 }
 return deferred.promise;
}
Promise.resolve()
 .then(function() {
 console.log('start');
 return counter(3);
 })
 .then(function() {
 console.log('ready');
 });
answered Mar 9, 2016 at 15:31
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.