I am doing a webapp with html + jquery and a java support service backend. I have a text box with sentences of type, so that each character that the user enters into the field initiates a workaround and updates the list of sentences of type
.
The main parts of the code:
var showTypeaheadSuggestions = function(data) { // update ui-element ... } var displayFailure = function() { // update ui-element ... } var searchText = $("#searchText"); var searchTextKeyup = function() { var txt = searchText.val(); $.ajax({ url : typeaheadUrl(txt), type : 'GET', dataType : 'json', }).done(showTypeaheadSuggestions).fail(displayFailure); } searchText.on('keyup', searchTextKeyup);
It basically works. But I was thinking about what would happen if you type, for example, 2 letters "ab" (this will first call the query "a" and then the query "ab") ...
Then, what happens if the answer "a" takes a little longer to process and comes after the answer "ab"? Do I need to detect this in my code to discard the answer "a"?
At http://api.jquery.com/jquery.ajax/ he says:
Promise callbacks -.done () ,. fail () ,. always () and .then () are called in the order in which they are registered.
What does it mean? I was hoping this means that $ .ajax () will automatically handle the above script correctly.
But when I do a little test (on the server side, I just entered a 2 s sleep delay, only when the search bar was exactly "a") it turns out that it does not behave as I expected.
The typeahead list will first be updated with the answer "ab", and then when the answer "a" arrives, it will also be updated, so the typeahead list gets the wrong suggestions.
What is the established way to handle this correctly?