gpt4 book ai didi

javascript - 如何实现可取消、有序的 promise ?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:16 26 4
gpt4 key购买 nike

我已经举了一个例子来证明我的意思:

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)">

在“搜索”框中键入内容并查看控制台。返回的搜索结果乱序!

当有新输入时,我们如何取消任何未决的 promise 并保证结果按顺序返回?

最佳答案

我没有使用去抖动或超时,而是在这个使用引用函数的函数中设置了少量状态 outside inside(Jaromanda X 的建议)。这样,您只需将函数引用更改为类似 noop 的内容。 promise 仍然 resolve,但它不会采取任何行动。然而,最后一个不会改变它的功能引用:

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)">

关于javascript - 如何实现可取消、有序的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41405832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com