Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

javascript - 我如何在Node.js(Javascript)中等待,我需要暂停一段时间(How Can I Wait In Node.js (Javascript), l need to pause for a period of time)

I'm developing a console like script for personal needs.

(我正在为个人需求开发类似脚本的控制台。)

I need to be able to pause for a extended amount of time, but, from my research, node.js has no way to stop as required.

(我需要能够暂停很长一段时间,但是,根据我的研究,node.js无法按需停止。)

It's getting hard to read users' information after a period of time... I've seen some code out there, but I believe they have to have other code inside of them for them to work such as:

(一段时间后,读取用户的信息变得越来越困难...我已经看到了一些代码,但是我相信他们必须在其中包含其他代码才能使他们工作,例如:)

setTimeout(function() {
}, 3000);

However, I need everything after this line of code to execute after the period of time.

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

For example,

(例如,)

//start-of-code
console.log('Welcome to My Console,');
some-wait-code-here-for-ten-seconds..........
console.log('Blah blah blah blah extra-blah');
//endcode. 

I've also seen things like

(我也看过类似的东西)

yield sleep(2000);

But node.js doesnt recognize this.

(但是node.js无法识别这一点。)

How can I achieve this extended pause?

(我如何才能实现这种长时间的暂停?)

  ask by Christopher Allen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A new answer to an old question.

(对旧问题的新答案。)

Today ( Jan 2017 June 2019) it is much easier.

(今天( 20171月,2019 6月)要容易得多。)

You can use the new async/await syntax .

(您可以使用新的async/await语法 。)

For example:

(例如:)

async function init(){
   console.log(1)
   await sleep(1000)
   console.log(2)
}
function sleep(ms){
    return new Promise(resolve=>{
        setTimeout(resolve,ms)
    })
}

For using async/await out of the box without installing and plugins, you have to use node-v7 or node-v8, using the --harmony flag.

(要使用开箱即用的async/await而不安装和使用插件,必须使用--harmony标志使用node-v7或node-v8。)

Update June 2019: By using the latest versions of NodeJS you can use it out of the box.

(2019年6月更新:通过使用最新版本的NodeJS,您可以立即使用它。)

No need to provide command line arguments.

(无需提供命令行参数。)

Even Google Chrome support it today.

(甚至谷歌浏览器也支持它。)

More info:

(更多信息:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...