哪些功能可以在node.js中充当同步功能? [英] Which functions could work as synchronous in node.js?

查看:83
本文介绍了哪些功能可以在node.js中充当同步功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我正在使用 crypto.randomBytes(...)以及另一个异步函数编写一个随机生成器。为了避免陷入回调地狱,我可以使用 crypto.randomBytes 的同步功能。我的疑问是我是否每次执行代码时都会停止节点程序?然后我想,如果有一个异步函数列表,它们的运行时间很短,它们可以用作同步函数,那么用这个函数列表进行开发将很容易。

For example, I am writing a random generator with crypto.randomBytes(...) along with another async functions. To avoiding fall in callback hell, I though I could use the sync function of crypto.randomBytes. My doubt is if I do that my node program will stop each time I execute the code?. Then I thought if there are a list of async functions which their time to run is very short, these could work as synchronous function, then developing with this list of functions would be easy.

推荐答案

使用 mz 模块,您可以使 crypto.randomBytes()返回承诺。使用 await (在节点7.x中使用-harmony 标志提供),您可以像这样使用它:

Using the mz module you can make crypto.randomBytes() return a promise. Using await (available in Node 7.x using the --harmony flag) you can use it like this:

let crypto = require('mz/crypto');

async function x() {
  let bytes = await crypto.randomBytes(4);
  console.log(bytes);
}

x();

上面的内容是 nonblocking ,即使它看起来正在阻止。

The above is nonblocking even though it looks like it's blocking.

为更好的演示,请考虑以下示例:

For a better demonstration consider this example:

function timeout(time) {
  return new Promise(res => setTimeout(res, time));
}

async function x() {
  for (let i = 0; i < 10; i++) {
    console.log('x', i);
    await timeout(2000);
  }
}

async function y() {
  for (let i = 0; i < 10; i++) {
    console.log('y', i);
    await timeout(3000);
  }
}

x();
y();

并且请注意,这两个函数需要花费很多时间来执行,但不会互相阻塞。

And note that those two functions take a lot of time to execute but they don't block each other.

使用以下节点在节点7.x上运行:

Run it with Node 7.x using:

node --harmony script-name.js

或与Node 8.x一起使用:

Or with Node 8.x with:

node script-name.js

我向您展示了这些示例,以证明它不是选择使用回调地狱和使用漂亮的代码进行异步。实际上,您可以使用新的 异步函数 await 运算符,位于 ES2017 -很好阅读,因为很少有人知道这些功能。

I show you those examples to demonstrate that it's not a choice of async with callback hell and sync with nice code. You can actually run async code in a very elegant manner using the new async function and await operator available in ES2017 - it's good to read about it because not a lot of people know about those features.

这篇关于哪些功能可以在node.js中充当同步功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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