I am facing an issue with a third-party library that I am listening to for events. When I try to modify the data it appends to the UI synchronously, everything works perfectly. However, once I introduce Ajax callbacks or promises into the mix, the functionality breaks down. Let me illustrate the problem with an example.
Here is how I am listening to an event:
d.on('gotResults', function (data) {
// Modifying data directly works fine.
data.title = 'newTitle';
// The above code successfully changes the text.
//I need to retrieve some properties from elsewhere so I make an Ajax call.
$.ajax('http://someurl...', {data.id}, function (res) {
data.someProperty = res.thatProperty;
});
// The above code does not wait for the Ajax call to complete and renders the page without the data change.
// I have also tried using promises but to no avail
return fetch('http://someurl...').then(function (data) {
data.someProperty = res.thatProperty;
return true;
});
// The above code also triggers the URL request and moves on without waiting for the promise to be fulfilled.
});
I am unable to alter the third party library itself. My only option is to listen to the event and modify the data accordingly.
Unfortunately, there are no better solutions available as I cannot use async/await or generators since I need to ensure compatibility with ES5 browsers.