Taras Yaremkiv Taras Yaremkiv - 27 days ago 19
Javascript Question

Delay return from function using promise

I'd like to run the function that consists of:
if condition is solved
1)add class
2)sleep 4 sec then remove class
3)then stop running function using return.

function sleep(time) {
return new Promise(resolve => {
setTimeout(resolve, time)
})
}
function playGame() {
if (counter === 3) {
Promise.resolve().then(function () {
message.classList.add('winner');
sleep(2500).then(function () {
message.classList.remove('winner');
});
});
return;
}
...
}


If I run this code, function returning immediately of course. How do I add return to the promise chain.

Answer

This should work:

Promise.resolve()
.then(function () {
    message.classList.add('winner');
})
.then(sleep(2500))
.then(function() {
    message.classList.remove('winner');
});

This should be self-explanatory. Feel free to ask more questions as needed.

EDIT : Oooops it seems that I answered this one too quickly. You can never postpone a "return" statement in javascript. In your case, your code, or mine executes immediately, and the return of the enclosing function is called immediately, and the execution goes back to the event loop. Then, the first then() of the promise is called, etc...

Since you can't postpone the return of the function, you use callbacks, or better, Promises, to chain events:

function playGame() {
    return Promise.resolve()  // note the return !
    .then(function () {
        message.classList.add('winner');
    })
    .then(sleep(2500))
    .then(function() {
        message.classList.remove('winner');
    });
}

...then

playGame()
.then(function() {
    // this code is called after playGame's Promise has been executed
});

To put it differently: once you begin to have asynchronous code (through callbacks or promises), every further code needs to be driven by promises, too.