I've put together an example to demonstrate what I'm getting at:
function onInput(ev) {
let term = ev.target.value;
console.log(`searching for "${term}"`);
getSearchResults(term).then(results => {
console.log(`results for "${term}"`,results);
});
}
function getSearchResults(term) {
return new Promise((resolve,reject) => {
let timeout = getRandomIntInclusive(100,2000);
setTimeout(() => {
resolve([term.toLowerCase(), term.toUpperCase()]);
}, timeout);
});
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
<input onInput="onInput(event)">
Type in the "search" box and watch the console. The search results come back out of order!
How can we cancel any pending promises when there's new input and guarantee the results come back in order?