I have a search input which with every keyup event a search to the backend is triggered to get the household information. But I have the issue that the requests are received out of order, for example if I try to look for the user with last name "wick" I have the following requests (leaving out the rest of the query params to make my point clearer):
- http://127.0.0.1:5560/api/household/?search_value=w
- http://127.0.0.1:5560/api/household/?search_value=wi
- http://127.0.0.1:5560/api/household/?search_value=wic
- http://127.0.0.1:5560/api/household/?search_value=wick
Then the results are totally random but most of the time the order is in reverse, I get 4) then 3) ... 1), so at the end the search result does not make any sense since I am looking for user "wick" but I get the results for user "w". This is my code:
let houseHoldSearchInput = document.getElementById("household-search-input");
window.addEventListener("load", (_event) => {
houseHoldSearchInput.addEventListener("keyup", keyupSearch, false);
});
async function keyupSearch(e){
let searchVal = e.target.value.trim().replace(" ", "+");
if (searchVal != "") {
let data = await getSearchResults(searchVal);
insertSearchOptions(data);
}
}
async function getSearchResults(searchVal){
return await get_household(searchVal, 1, 30, "first_name", "desc");
}
export function get_household(search_value, page, page_size, sort_by, sort_order) {
return fetch(api_server + `/api/household/?search_value=${search_value}&page=${page}&page_size=${page_size}&sort_by=${sort_by}&sort_order=${sort_order}`, {
method: "GET",
headers: {
"Authorization": `Bearer ${jwt}`,
},
}).then( res => {
return res.json();
}).then( data => {
data.data.sort(function (a, b) { return `${a.first_name} ${a.last_name}`.localeCompare(`${b.first_name} ${b.last_name}`) });
return data.data;
}).catch( err => console.log(err))
}
Then, I get the results from the requests in random order, even when using async/await and this problem has given me a lot of problems now. I never had such a problem using the popular HTTP clients from Angular or React, but in this project everything is vanilla JavaScript, for some crazy reason, at this modern age, they decided to go for it instead of a mature framework. Some pointers to get the order in a sequential fashion would be really appreciated.
How to get multiple fetch functions execute in order? and What is the "debounce" function in JavaScript? don't answer the question as they don't allow running multiple requests in parallel or dropping outdated requests. An example of why it's wanted may be very high ping and very long typed strings, leading to either very slow or very rare updates if the above answers are user