While going through the definition for pure functions, it's generally defined with two traits:
1) Should produce same output given the same input
2) Should not produce any side effects
Does it also imply that a pure function shouldn't be asynchronous? If no, how so? If yes, I would love to see some examples of asynchronous pure function in JavaScript.
While going through the definition for pure functions, it's generally defined with two traits:
1) Should produce same output given the same input
2) Should not produce any side effects
Does it also imply that a pure function shouldn't be asynchronous? If no, how so? If yes, I would love to see some examples of asynchronous pure function in JavaScript.
Share Improve this question asked Oct 6, 2018 at 15:20 Anish K.Anish K. 2,5323 gold badges22 silver badges27 bronze badges 3-
In your opinion, does
new Promise(() => {}) !== new Promise(() => {})
violate trait 1? Other than not being the same object, the promises behave identically. – Patrick Roberts Commented Oct 6, 2018 at 15:31 - 1 @PatrickRoberts I guess it does violate the rule#1, since technically my outputs won't be the same while calling the same function twice. – Anish K. Commented Oct 6, 2018 at 15:35
- 2 Disagree - if referential equality is a requirement for purity, then any function that returns an object in javascript could not be considered pure. – dvlsg Commented Oct 6, 2018 at 19:57
2 Answers
Reset to default 14Yes, an asynchronous function usually isn't pure, as it conflicts with requirement #2: no side effects.
Most things that we use asynchronous functions for are inherently side-effectful: I/O, network stuff, timers. But even if we ignore those, promises alone rely on some kind of global state for their asynchrony: the event loop. This typically doesn't fit within our definition of purity.
On the other hand, we can simply ignore those when arguing about purity of our functions, just as we ignore all the low-level effects and timings that a putation has on our real-world machine. If you want to argue that your asynchronous function is pure, you should however always state this assumption explicitly. When arguing about the equivalence of two asynchronous values, you will need to have a sophisticated idea of how you model asynchronous effects, e.g. in the evaluation of Promise.race
.
yes, async functions are no different from regular functions except that async means it returns Promise<T>
rather just T
, with that said, this is the only difference from the sync functions which can be pure, hence async functions can be pure too
example:
async function willBeValue<T>(value: T): Promise<T> { return await value; }