CHADTO
CHADTO

Reputation: 351

Wait for a function until it has finished its setTimeout function

i want to know if there is a way i can wait for a function that has a structure similar to this :

function foo(){
    //do stuff
    setTimeout(()=>{
     
       //do more stuff

    },timeout)

    // do even more stuff

}

i tried using utils.promisify but it tends not to wait for the settimeout to finish before proceeding to the "then" callback function.

here is an example :

const promise=promisify(foo);
promise().then(alert("ok"));

the alert seems to trigger way before the settimeout is finished executing.

Upvotes: 0

Views: 1897

Answers (1)

David Aguilar
David Aguilar

Reputation: 13

I think you should try using the Promise constructor and resolve or reject

let  a = new Promise( function(resolve, reject) { setTimeout(
    function() {
      resolve("whatever");
    }, timeout});

a.then(alert("ok"));

Upvotes: 1

Related Questions