我正在为个人需要开发一个控制台脚本。我需要能够暂停更长的时间,但根据我的研究,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并不认识到这一点。
我如何实现这种延长的暂停?
最好的方法是将代码分解成多个函数,如下所示:
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的解决方案类似,但更简洁,更易于扩展。
2021年1月更新:您甚至可以使用--experimental-repl-await
标志在节点REPL interactive中进行此操作
$ node --experimental-repl-await
> const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
> await delay(1000) /// waiting 1 second.
老问题的新答案。今天(2017年1月2019年6月)要轻松得多。您可以使用新的async/await
语法。例如:
async function init() {
console.log(1);
await sleep(1000);
console.log(2);
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
若要在不安装和插件的情况下立即使用Async/Await
,您必须使用node-v7或node-v8,使用--harmony
标志。
2019年6月更新:通过使用最新版本的NodeJS,您可以开箱即用。不需要提供命令行参数。今天甚至谷歌Chrome也支持它。
2020年5月更新:不久您将能够在异步函数之外使用await
语法。在顶层中,如本例所示
await sleep(1000)
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
该提案处于第三阶段。您现在可以通过使用WebPack5(alpha)来使用它,
更多信息: