有一个类Search指向服务器并返回结果。对服务器的调用在事件上挂起input。如何在Search. 思路中,就是在属性上挂一个promise result,但是期望执行一次,但是每次匹配都需要执行。可以通过其他方式完成吗?
为了确保最后一个请求得到处理,我使用了this.query_id != query_id,但我不喜欢在三个地方使用它。我该如何解决?
我想使用AbortController,但它取消了所有订阅它的执行。
UPD:
您可以将处理程序传递给方法init(fn)或属性result以使其成为对象并将其包装在代理中,哪个更正确?
function makeid() {
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 3; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
text += Math.floor(Math.random() * (99999 - 10000)) + 10000;
return text;
}
class Search {
search_field = document.getElementById('search');
search_mirror = document.getElementById('mirror');
query_id;
result;
constructor() { }
init() {
this.result = new Promise((resolve) => {
this.search_field.oninput = this.runSearch.bind(this, resolve);
});
}
runSearch(resolve) {
if (this.search_field.value.length < 0) return false;
const url = `https://httpbin.org/post`;
const query_id = makeid();
this.query_id = query_id;
fetch(url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: this.search_field.value
})
}).then((response) => {
if (response.status === 200) {
return response.json();
} else {
throw new Error("ERR-167: Ошибка соединения с сервером!");
}
}).then(
(result) => {
if (this.query_id != query_id) return true;
let res = result.json.message;
this.search_mirror.innerText = res;
if (res == 'xxx') resolve(res);
},
(err) => {
if (this.query_id != query_id) return true;
console.error(err);
}
).finally(() => {
if (this.query_id != query_id) return true;
console.log('done');
});
}
}
let search = new Search();
search.init();
search.result.then(
res => {
alert('goal');
console.log(res);
}
);
<input type="text" value="" id="search" placeholder="xxx">
<div id="mirror"></div>
我不确定这个决定的正确性,也许吧。无论如何都会在类中处理响应
Search,但可以从外部设置处理程序