我正在为个人需求开发一个控制台脚本。我需要能够暂停更长的时间,但是,根据我的研究,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不能识别这个。

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


当前回答

let co = require('co');
const sleep = ms => new Promise(res => setTimeout(res, ms));

co(function*() {
    console.log('Welcome to My Console,');
    yield sleep(3000);
    console.log('Blah blah blah blah extra-blah');
});

This code above is the side effect of the solving Javascript's asynchronous callback hell problem. This is also the reason I think that makes Javascript a useful language in the backend. Actually this is the most exciting improvement introduced to modern Javascript in my opinion. To fully understand how it works, how generator works needs to be fully understood. The function keyword followed by a * is called a generator function in modern Javascript. The npm package co provided a runner function to run a generator.

本质上,生成器函数提供了一种使用yield关键字暂停函数执行的方法,同时,生成器函数中的yield使生成器内部和调用者之间交换信息成为可能。这为调用方提供了一种机制,可以从异步调用的promise中提取数据,并将已解析的数据传递回生成器。实际上,它使异步调用同步化。

其他回答

这个问题很老了,但是最近V8增加了生成器,可以完成OP的请求。在挂起或gen-run等库的帮助下,生成器通常最容易用于异步交互。

下面是一个使用suspend的例子:

suspend(function* () {
    console.log('Welcome to My Console,');
    yield setTimeout(suspend.resume(), 10000); // 10 seconds pass..
    console.log('Blah blah blah blah extra-blah');
})();

相关阅读(通过无耻的自我宣传):发电机有什么大不了的?

对于一些人来说,接受的答案是不工作的,我发现了这个其他的答案,它是为我工作:我如何传递一个参数setTimeout()回调?

var hello = "Hello World";
setTimeout(alert, 1000, hello); 

'hello'是正在传递的参数,您可以在超时时间后传递所有参数。感谢@Fabio Phms的回答。

你可以使用这个www.npmjs.com/package/sleep

var sleep = require('sleep');
sleep.sleep(10); // sleep for ten seconds

节点16有一种新的方法可以轻松地完成它

import { setTimeout } from 'timers/promises'

console.log('before')
await setTimeout(3000)
console.log('after')

有关更多信息

yield sleep(2000); 

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