Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can pure functions be asynchronous?

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.

like image 519
Anish K. Avatar asked Oct 06 '18 15:10

Anish K.


2 Answers

Yes, 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 computation 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.

like image 186
Bergi Avatar answered Sep 19 '22 15:09

Bergi


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; }
like image 38
Trident D'Gao Avatar answered Sep 20 '22 15:09

Trident D'Gao