by cookiesboxcar · 9y ago · 0 comments
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?
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.)
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.
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).