In my node.js backend I have this global variable, which is a key-value set.
responses = {};
Entries are continuously created by an asynchronous task
function responseContinuousFetching(){
axios.get(url,
).then((response) => {
responses[response.guid] = response.payload;
setTimeout(()=>responseContinuousFetching(), 1);
}).catch(error) {
[handle errors]
setTimeout(()=>responseContinuousFetching(), 1);
};
};
Another asynchrounous task checks this key-value set. When the right id is found the entry is removed from the set
api.post(url, jsonParser, (req.res) => {
const params = req.body;
[some synchronous code]
let found = false;
while (!found) {
if responses.hasOwnProperty(req.body.guid) {
response = responses(req.body.guid);
delete responses[req.body.guid];
found = true;
}
}
return response;
});
(For clarity: the "responseContinuousFetching" is done by the backend to an external API, while the second block is the definition of an entrypoint, which is exposed by the backend to a frontend)
This obviously doesn't work, as the while loop is synchronous code which monopolizes the backend, preventing the update of the object "responses". The result is that the while loop goes on forever and the backend is stuck.
I was wondering if there is any way to access asynchronously to local variables, allowing other tasks that are waiting in the event loop to be executed.
Thanks,
Thomas