Search code examples
javascriptnode.jstypescript

Why do some libraries expose methods that does the same thing, but each in sync/async context?


Some libraries exposes two methods that essentialy does the same thing, but one of them runs in async context and the other in sync context.

Some examples are: unlink from fs/promises and unlinkSync from fs; compare, compareSync, hash and hashSync from bcrypt.

Why did they choose to do this? Is there any pros and cons of using sync or async depending on the context of my application?


Solution

  • Is there any pros and cons of using sync or async depending on the context of my application?

    Absolutely. Synchronous operations block the event loop, meaning that no other code can run while that is happening. Suppose you have some expensive hash operation (one with a lot of rounds) and you use hashSync.

    This will block the event loop while the hash is being calculated and in the case of running a web server using node.js, this means that any requests sent to your server during this time will be delayed until that operation is finished. This is why you use await with hash so you tell node.js to not block the event loop and run the code after it when the hashing operation has finished (like a callback).