我如何在 Node.js (JavaScript) 中等待?我需要暂停一段时间 [英] How can I wait In Node.js (JavaScript)? l need to pause for a period of time

查看:32
本文介绍了我如何在 Node.js (JavaScript) 中等待?我需要暂停一段时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为个人需要开发一个控制台脚本.我需要能够暂停很长时间,但是,根据我的研究,Node.js 无法按要求停止.一段时间后,阅读用户的信息变得越来越困难......我看到了一些代码,但我相信他们必须在其中包含其他代码才能工作,例如:

I'm developing a console script for personal needs. I need to be able to pause for an extended amount of time, but, from my research, Node.js has no way to stop as required. 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.

例如

    // 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 无法识别这一点.

But Node.js doesn't recognize this.

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

How can I achieve this extended pause?

推荐答案

2021 年 1 月更新:您甚至可以在 Node REPL 交互中使用 --experimental-repl-await 标志

Update Jan 2021: You can even do it in the Node REPL interactive using --experimental-repl-await flag

$ node --experimental-repl-await
> const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
> await delay(1000) /// waiting 1 second.

一个老问题的新答案.今天(Jan 2017 June 2019)要容易得多.您可以使用新的async/await语法.例如:

A new answer to an old question. Today ( Jan 2017 June 2019) it is much easier. You can use the new async/await syntax. For example:

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 标志.

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.

2019 年 6 月更新:通过使用最新版本的 NodeJS,您可以开箱即用.无需提供命令行参数.今天甚至 Google Chrome 也支持它.

Update June 2019: By using the latest versions of NodeJS you can use it out of the box. No need to provide command line arguments. Even Google Chrome support it today.

2020 年 5 月更新:很快,您将能够在异步函数之外使用 await 语法.在这个例子中的顶层

Update May 2020: Soon you will be able to use the await syntax outside of an async function. In the top level like in this example

await sleep(1000)
function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

提案处于第 3 阶段.你今天可以通过使用 webpack 5 (alpha) 来使用它,

The proposal is in stage 3. You can use it today by using webpack 5 (alpha),

更多信息:

这篇关于我如何在 Node.js (JavaScript) 中等待?我需要暂停一段时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆