I am making a Javascript page that requests data on user events
A lot of data needs to be retrieved per event, so I get a small amount of the data with a single AJAX request so I can show updates. The callback recursively requests more data via AJAX until there's no data left to get. Within this "chain", everything goes well.
Problems, however, arise when an user fires more events when a different chain is already running. Both chains use the same data object, so data gets lost. What is the proper way to queue these user events so they don't run concurrently? I've added a mutex (https://github.com/kirill-konshin/mutex-promise) but that doesn't take into account the AJAX request.
General code structure:
function userEvent(){
exclusiveGetData()
}
var dataCache = [];
var getDataMutex = new MutexPromise('ThisIsAnUniqueEnoughKey');
function exclusiveGetData(){
return getDataMutex.promise()
.then(function(){
getDataMutex.lock();
getData();
})
.then(function(res){
getDataMutex.unlock();
return res;
})
.catch(function(e){
getDataMutex.unlock();
throw e;
});
}
function getData(){
$.get("url", function(data){
dataCache.handleData();
if(thereIsMoreData)
getData();
})
}
This of course doesn't work because we don't wait for $.get() to finish before releasing the lock. I'm pretty sure I need promises, but I've been fiddling around with those for about 4 hours and I haven't gotten it to work yet. Any advice?