javascript - Delay return from function using promise -


i'd run function consists of: if condition solved 1)add class 2)sleep 4 sec 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 run code, function returning of course. how add return promise chain.

this should work:

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

this should self-explanatory. feel free ask more questions needed.

edit : oooops seems answered 1 quickly. can never postpone "return" statement in javascript. in case, code, or mine executes immediately, , return of enclosing function called immediately, , execution goes event loop. then, first then() of promise called, etc...

since can't postpone return of function, use callbacks, or better, promises, chain events:

function playgame() {     return promise.resolve()  // note return !     .then(function () {         message.classlist.add('winner');     })     .then(sleep(2500))     .then(function() {         message.classlist.remove('winner');     }); }  ...then  playgame() .then(function() {     // code called after playgame's promise has been executed });  // code called when playgame ends, ie immediately, , before promises code 

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


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -