我正在为个人需求开发一个控制台脚本。我需要能够暂停更长的时间,但是,根据我的研究,Node.js没有办法根据需要停止。一段时间后,读取用户信息变得越来越困难了……我已经看到了一些代码,但我相信他们必须有其他的代码在他们的工作,如:

    setTimeout(function() {
    }, 3000);

但是,我需要这行代码之后的所有内容在一段时间之后执行。

例如,

    // start of code
    console.log('Welcome to my console,');

    some-wait-code-here-for-ten-seconds...

    console.log('Blah blah blah blah extra-blah');
    // end of code

我还见过

    yield sleep(2000);

但是Node.js不能识别这个。

我怎样才能实现这种延长的暂停?


当前回答

有关更多信息

yield sleep(2000); 

你应该检查Redux-Saga。但是它是特定于您选择Redux作为模型框架的(尽管严格来说不是必需的)。

其他回答

最好的方法是把你的代码分解成多个函数,像这样:

function function1() {
    // stuff you want to happen right away
    console.log('Welcome to My Console,');
}

function function2() {
    // all the stuff you want to happen after that pause
    console.log('Blah blah blah blah extra-blah');
}

// call the first chunk of code right away
function1();

// call the rest of the code and have it execute after 3 seconds
setTimeout(function2, 3000);

它类似于JohnnyHK的解决方案,但更整洁,更容易扩展。

我最近创建了一个更简单的抽象概念,叫做等待。用于在同步模式下调用异步函数(基于节点光纤)。还有一个基于即将到来的ES6生成器的版本。

https://github.com/luciotato/waitfor

使用等。对于,你可以调用任何标准的nodejs async函数,就像它是一个同步函数一样,而不会阻塞node的事件循环。

您可以在需要时按顺序编码,这(我猜)完美地简化了您的脚本供个人使用。

使用等。你的代码将是:

require('waitfor')

..in a fiber..
//start-of-code
console.log('Welcome to My Console,');
wait.miliseconds(10*1000); //defined in waitfor/paralell-tests.js - DOES NOT BLOCK
console.log('Blah blah blah blah extra-blah');
//endcode. 

同样,任何async函数都可以在Sync模式下调用。 检查例子。

function doThen(conditional,then,timer) {
    var timer = timer || 1;
    var interval = setInterval(function(){
        if(conditional()) {
            clearInterval(interval);
            then();
        }
    }, timer);
}

使用示例:

var counter = 1;
doThen(
    function() {
        counter++;
        return counter == 1000;
    },
    function() {
        console.log("Counter hit 1000"); // 1000 repeats later
    }
)

如果你只是为了测试而挂起当前线程执行,试试这个:

function longExecFunc(callback, count) {

    for (var j = 0; j < count; j++) {
        for (var i = 1; i < (1 << 30); i++) {
            var q = Math.sqrt(1 << 30);
        }
    }
    callback();
}
longExecFunc(() => { console.log('done!')}, 5); //5, 6 ... whatever. Higher -- longer

从Node.js 15及以上版本开始,你可以使用Timers Promises API。您不再需要承诺setTimeout或依赖第三方库。

import { setTimeout } from 'timers/promises';

await setTimeout(1000);