Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay the return of a function

Is there anyway to delay the return of a function using setTimeout()?

function foo(){
  window.setTimeout(function(){
      //do something
  }, 500);
 //return "something but wait till setTimeout() finishes";
}
like image 953
khousuylong Avatar asked Feb 03 '23 17:02

khousuylong


1 Answers

Using promises:

const fetchData = () =>
  new Promise(resolve => {
    setTimeout(() => resolve(apiCall()), 3000);
  });

Answer updated thanks to @NikKyriakides who pointed out async/await is not necessary. I initially had async () => resolve(await apiCall()).

like image 50
Nelu Avatar answered Feb 05 '23 15:02

Nelu