0

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.

Serg
  • 2,346
  • 3
  • 29
  • 38
CHADTO
  • 331
  • 1
  • 4
  • 12
  • 2
    Does this answer your question? [Combination of async function + await + setTimeout](https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout) – Harmandeep Singh Kalsi Jul 16 '20 at 14:07
  • 1
    `alert` is called first because you call it first. You have to pass a function reference to `.then`: `.then(() => alert('ok'))`. `promisify` will still not work because `foo` isn't a function that can be promisified. Look at the linked question to learn how to properly combine promises and `setTimeout`. – Felix Kling Jul 18 '20 at 19:07
  • No, there is no way to wait for that function. You will need to change its structure so that it accepts a callback or returns a promise. – Bergi Jul 18 '20 at 21:05

1 Answers1

1

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"));