Which functions could work as synchronous in node.

2019-07-26 23:51发布

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.

2条回答
做个烂人
2楼-- · 2019-07-27 00:21

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();

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.

Run it with Node 7.x using:

node --harmony script-name.js

Or with Node 8.x with:

node script-name.js

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.

查看更多
该账号已被封号
3楼-- · 2019-07-27 00:24

They're asynchronous, learn to deal with it.

Promises now, and in the future ES2017's await and async will make your life a lot easier.

Bluebirds promisifyAll is extremely useful when dealing with any standard Node.js callback API. It adds functions tagged with Async that return a promise instead of requiring a callback.

const Promise = require('bluebird')
const crypto = Promise.promisifyAll(require('crypto'))

function randomString() {
  return crypto.randomBytesAsync(4).then(bytes => {
    console.log('got bytes', bytes)
    return bytes.toString('hex')
  })
}

randomString()
  .then(string => console.log('string is', string))
  .catch(error => console.error(error))
查看更多
登录 后发表回答