Delay the return of a function

Viewed 28262

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";
}
4 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()).

Related