Hacker News new | ask | show | jobs
by cookiesboxcar 3407 days ago
Serious question: what is considered async?

From the site, I get that add(1+1) doesn't require a callback, whereas downloadFile(url) does.

What about somethingHarderThanAddition(noExternalDependency)?

My question is, what is the threshold that I can assume that my code will run sync, and when it cant?

3 comments

> what is the threshold that I can assume that my code will run sync, and when it cant?

Generally you won't have a choice. If something in your function calls another async function, the function as a whole is forced to be async. If not, then it won't be.

It's possible to make a function fake-async even if it doesn't call any async functions, by just calling the callback at the end. But there's not much point -- and callers may make assumptions about the the callback being called in a separate iteration of the event loop, so doing that could cause subtle bugs. That latter problem is solvable by calling the callback in a setImmediate callback, but again, no point unless you have a good reason to.

(Exception: there are a few apis where you do have a choice, e.g node's randomBytes can be either sync or async. Generally they're things that might block, where the sync version returns an error if it can't satisfy immediately. But generally you don't.)

Anything that suspends processing and waits for the OS to provide some data (file, time, socket, or piping usually) should be behind a callback. Beyond that benefit is more limited (in a single threaded app like NodeJS), since you are no longer using async to do othe stuff while you wait for resources. However, if the computation locks up the thread for too long, it cannot service callbacks, and so timers might be delayed, heartbeat messages might be skipped leading to dropped connections, and other bad stuff. If that's the case you want to either split your large computation into many smaller ones (allowing other callbacks to fire in between) or offload the computation into another process or thread.

In other words, it's an engineering decision, based on the expected consequences of the overall design in the context of understanding how the event reactor works.

>My question is, what is the threshold that I can assume that my code will run sync, and when it cant?

It will always run sync, unless you call something that accepts a callback (either at the first level, or nested in something else you call).