In my web project using angularjs, I have the task of downloading data every second via a WebSocket. However, I encounter issues with handling multiple requests of different types. Although I utilize Promises to structure the requests, sometimes the responses end up in the wrong function. To provide an example:
I've created a service responsible for making the requests and receiving Promise-based results.
socketService.$inject = [];
function socketService(){
let service = this;
let server = new WebSocket('ws://localhost:8090');
let isOpen = false;
server.onopen = function(){
isOpen = true;
};
server.onerror = function(){
//TODO handle error
};
service.sendRequest = function(action, data){
return new Promise(function (resolve, reject) {
if (isOpen) {
server.send(encodeRequest(action, data));
server.onmessage = function (message) {
resolve(JSON.parse(message.data));
}
}
server.onopen = function () {
server.send(encodeRequest(action, data));
server.onmessage = function(message) {
resolve(JSON.parse(message.data));
isOpen = true;
}
};
server.onerror = function (error) {
reject(error);
}
})
};
}
This is how I use it:
socketService.sendRequest('get_events', {})
.then(function (response) {
//DO SOMETHING WITH THE RESPONSE
return socketService.sendRequest('get_history', {
fromDate: value,
toDate : value,
tag : value,
event : value
})
})
.then(function (response) {
//DO SOMETHING WITH THE RESPONSE
});
The issue arises when I make concurrent requests. If I trigger multiple requests within seconds and then introduce a new request at the same time, the responses become mixed up. It seems that if I send a request and before its response, another request is made, the first response goes to the second request.
I am puzzled by this behavior as I'm returning a new Promise each time, which should associate the response with the correct Promise instead of mixing them up.
While I've learned that a resolved Promise cannot be reused (it will return the last result), I continuously create new ones. Can someone shed light on what might be happening and suggest potential solutions?