3 ms·
> Yes - shared data can be modified in between events on the event loop. I think the problem is more that data can be modified between an event occurring and t
by xg15 5y ago
> Yes - shared data can be modified in between events on the event loop.
I think the problem is more that data can be modified between an event occurring and the handlers for that very event being called.
I think we often conflate the time an event occurs with the time the event's handler is executed - when in reality, there can be an arbitrary, nontrivial delay between them due to queuing.
This means that any state invariants that an event might establish can already be long broken by the time your handler is called.
E.g., suppose you write database code in NodeJS and query an external SQL database. Your NodeJS process is single-threaded, uses only a single database connection and there is no other process interacting with the database either. Then the following code might seem safe:
let flaggedThings = await db.query("SELECT * FROM things WHERE flag = true");
process(flaggedThings) // assume each thing has the flag set to true
However, it's not. After the DB query returned, there will be some internal call to Promise.resolve() which will advance the script past the await. However, the event of the DB query returning will not immediately cause this call - it will only cause a task for the call to be added to the event queue. But at the time the event loop dequeues and executes the task, other tasks, which were dequeued earlier, might already have changed the DB state.
Therefore, the resultset may already be stale at the moment the script continues after the await.