I have an AngularJS controller that is making asynchronous calls to a service that returns promises.
$myService.getData(ctrl.state)
.then(function(data) {
updateInterface(data);
});
When the promises return, I am updating data in the interface. However, if I make two calls, and the first call returns after the second call, then the interface will update with the incorrect data, based on stale state.
I have thought of a few ways of dealing with this problem:
- Keep track of some sort of identifier of the promise, and when a promise returns, only handle it if it matches the latest.
- Keep track of a promise until it returns. If another call is made, cancel the promise. The canceling could be handled by the service.
The getData method makes an ajax call ($http.get
), so I could could cancel that by calling resolve()
on the _httpTimeout
object. However this seems very specific to the logic within the promise.
Are there best practices for handling this async issue? JsFiddle is here.
var testDiv = document.getElementById('test');
function loadData(query, pause) {
var data = query;
return new Promise((resolve, reject) => {
setTimeout(function() {
resolve(data);
}, pause);
});
}
var test = function(query, pause) {
loadData(query, pause)
.then(function(data) {
console.log("got back test data", data);
testDiv.innerHTML = data;
});
};
test("first", 1000);
test("second", 0);
<div id="test">
</div>