30-seconds-of-code: Why hashNode return sha256 hex in next tick?

Created on 10 Jan 2019  路  10Comments  路  Source: 30-seconds/30-seconds-of-code

Description

Is there some security reasons?

All 10 comments

I'm not exactly sure. I'm pretty certain you could easily just do

const hashNode = val => Promise.resolve(crypto
  .createHash('sha256')
  .update(val)
  .digest('hex')
)

@Chalarangelo is there a reason that's done?

That's one of the oldest snippets, I think we kind of adapted this from some StackOverflow answer, so that's why it looks that way. If the way it works and its use cases are not altered, we should update it to this new version.

IMO. Promise is unnecessary here also.

  1. It cannot avoid process blocking.
  2. It cannot provide result memo.

Two reasons why we are using a promise here:

  1. Hashing is quite expensive, so a promise is preferred to make sure the thread doesn't wait for a long time.
  2. The footprint matches the browser footprint, which is somewhat nice.

I am pretty sure we should stick to this returning a promise, just clean up the code a bit. Plus, it's gonna be a breaking change and this is quite a popular snippet in my experience.

@Chalarangelo this is a blocking stream, wrapping it in a promise merely delays when you can use it, which would mean that it actually works as finish hash, update hash, next available loop return hash.

Although I think this answers why we put it on next tick. By putting it on next tick we offload it until the event loop is free, which since these algorithms can be heavy would in fact be preferred than randomly running a blocking hash out of nowhere.

@cncolder Looks like we remembered why it's done next tick. It's to prevent a long blocking operation and use the event loop to allow for other operations to finish being queued instead of delayed in case of a large hashing operation(everything that gets added after will be delayed though)

My suggestion is that hashNode is updated to explain why it uses the setTimeout so as to put it onto the event loop and not block

@skatcat31 My thoughts exactly. Could you PR an update for the explanation, just so we remember why this is done like this next time? 馃槢

Sure. When I get home tomorrow I'll issue the pr

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for any follow-up tasks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ecwyne picture ecwyne  路  4Comments

skatcat31 picture skatcat31  路  5Comments

fuchao2012 picture fuchao2012  路  4Comments

emelendez picture emelendez  路  4Comments

Chalarangelo picture Chalarangelo  路  5Comments