如何在 javascript 函数返回值之前添加延迟

how to add delay before returning a value in javascript function

我需要在 Javascript 函数返回值之前添加 2 秒的延迟

function slowFunction(num) {
  console.log("Calling slow function");
 
  // 2 seconds delay here

  return num * 2;
}

有几种方法可以做到这一点。

我更喜欢使用 promises。

function sleep(delay: number): Promise<void>{
   return new Promise( (res) => {
        setTimeout(()=>res(),delay)
   })
}

async function slowFunction(num) {
  console.log("Calling slow function");
  await sleep(2000)
  // 2 seconds delay here

  return num * 2;
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function