javascript-如何实现可取消的,有序的诺言?
作者:互联网
我整理了一个例子来说明我要得到的是:
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)">
标签:promise,es6-promise,javascript 来源: https://codeday.me/bug/20191026/1936162.html