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.
相关问题
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- google-drive can't get push notifications
- How to reimport module with ES6 import
- Why it isn't advised to call the release() met
- Why is `node.js` dying when called from inside pyt
相关文章
- node连接远程oracle报错
- How can make folder with Firebase Cloud Functions
- @angular-cli install fails with deprecated request
- node.js modify file data stream?
- How to resolve hostname to an ip address in node j
- Transactionally writing files in Node.js
- Log to node console or debug during webpack build
- With a Promise, why do browsers return a reject tw
Using the
mz
module you can makecrypto.randomBytes()
return a promise. Usingawait
(available in Node 7.x using the--harmony
flag) you can use it like this:The above is nonblocking even though it looks like it's blocking.
For a better demonstration consider this example:
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:
Or with Node 8.x with:
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
andawait
operator available in ES2017 - it's good to read about it because not a lot of people know about those features.They're asynchronous, learn to deal with it.
Promises now, and in the future ES2017's
await
andasync
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 withAsync
that return a promise instead of requiring a callback.