I recently dived into subscriptions of Subject/BehaviorSubject/ etc and I am looking for the goto approach when used in combinations with Promises.
Given is the example code below:
firebase.user.subscribe((user: any | null) => {
fs.readFile('path/to/file')
.then((buf: Buffer) => {
this.modifySomeData = buf;
});
});
I subscribe to a Subject that triggers whenever the user logs in or out of their service. Whenever this happens, I read a file from disk. This readFile
event could potentially take longer than the next "login/logout" event. Of course, I am in JS and in an asynchronous environment. This means, my user code is not multithreaded, but still, the 2nd user event and 2nd readFile
could theoretically be faster than the first readFile
.
- First user event fired
- First readFile is executed
- Second user event is fired
- Second readFile is executed
- Second readFile is resolved <---
- First readFile is resolved <---
The order is mixed up. The silliest approach I could think of is to create a uuid
before reading the file and check inside the promise if this is still the same. If it's not I discard the data.
Is there a better solution?