Reputation: 782
Is it possible to assume that a function that does not return a Promise or an Observable is synchronous functions in JavaScript. If not how to know whether a function is sync or a-sync.
Upvotes: 0
Views: 52
Reputation: 782130
Promises are a relatively recent addition to Javascript, but there have been asynchronous functions for much longer. The older asynchronous functions do not return a promise. Examples:
XMLHttpRequest.send
setTimeout
addEventListener
If a function takes a callback function as an argument, and the function's return value depends the result of that callback, then the function has to be synchronous. Async functions can never return the result of the callback, since it's called after the function returns.
So, for instance, all the array-processing functions like map
, filter
, and reduce
, must be synchronous because they return arrays whose contents are dependent on the callback function.
Upvotes: 1
Reputation: 709
No, it is not possible to determine whether a method (that does not return a promise or observable) is synchronous or not synchronous. I could take a regular synchronous method and add a call to an asynchronous function to it. From the outside, it looks the same - but now it is queueing up (triggering, whatever your favorite terminology) some asynchronous work. As mentioned above, another key function signature is one that takes a callback handler - if it does, it is likely (though, to be pedantic, not necessarily) asynchronous. But assuming a function does none of those things, you can't really know.
You may not care about that asynchronicity - you may only care whether what you think the method is doing completes before it returns or not, and that may be obvious from its return type. For instance addTwoNumbers(a: number, b: number): number
clearly is synchronous in terms of returning the result, but, as I mentioned above, it could have spawned some asynchronous work (e.g. logging something to a file) and you'd never know from the function signature.
Upvotes: 1