我整理了一个例子来说明我要得到的是:
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)">
当有新的输入时,我们如何取消任何未完成的承诺并保证结果按顺序返回?
解决方法:
我没有使用去抖动或超时,而是在使用引用函数的该函数的内部(Jaromanda X建议)设置了少量状态.这样,您可以将函数引用更改为类似noop的内容.承诺仍然可以解决,但不会采取任何行动.但是,最后一个不会更改其功能参考:
var onInput = function() {
let logger = function(term, results) {
console.log(`results for "${term}"`, results);
};
let noop = Function.prototype;
let lastInstance = null;
function ActionManager(action) {
this.action = action;
}
return function onInput(ev) {
let term = ev.target.value;
console.log(`searching for "${term}"`);
if (lastInstance) {
lastInstance.action = noop;
}
let inst = new ActionManager(logger.bind(null, term));
lastInstance = inst;
getSearchResults(term).then(response => inst.action(response));
}
}();
/****************************************
* The rest of the JavaScript is included only for simulation purposes
****************************************/
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)">
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。