How to create a sleep/delay in nodejs that is Blocking?

后端 未结 12 670
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 07:00

I\'m currently trying to learn nodejs and a small project I\'m working is writing an API to control some networked LED lights.

The microprocessor controlling the LED

12条回答
  •  不知归路
    2020-12-02 07:22

    With ECMA script 2017 (supported by Node 7.6 and above), it becomes a one-liner:

    function sleep(millis) {
      return new Promise(resolve => setTimeout(resolve, millis));
    }
    
    // Usage in async function
    async function test() {
      await sleep(1000)
      console.log("one second has elapsed")
    }
    
    // Usage in normal function
    function test2() {
      sleep(1000).then(() => {
        console.log("one second has elapsed")
      });
    }
    

提交回复
热议问题