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

后端 未结 12 667
爱一瞬间的悲伤
爱一瞬间的悲伤 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:23

    You can simply use yield feature introduced in ECMA6 and gen-run library:

    let run = require('gen-run');
    
    
    function sleep(time) {
        return function (callback) {
            setTimeout(function(){
                console.log(time);
                callback();
            }, time);
        }
    }
    
    
    run(function*(){
        console.log("befor sleeping!");
        yield sleep(2000);
        console.log("after sleeping!");
    });
    

提交回复
热议问题