假设我有这些数据spanish.json
:
[
{"word": "casa", "translation": "house"},
{"word": "coche", "translation": "car"},
{"word": "calle", "translation": "street"}
]
我有一个 Dictionary 类来加载它并添加一个搜索方法:
// Dictionary.js
class Dictionary {
constructor(url){
this.url = url;
this.entries = []; // we’ll fill this with a dictionary
this.initialize();
}
initialize(){
fetch(this.url)
.then(response => response.json())
.then(entries => this.entries = entries)
}
find(query){
return this.entries.filter(entry =>
entry.word == query)[0].translation
}
}
我可以实例化它,并使用它通过这个小单页应用程序查找“调用”:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>spanish dictionary</title>
</head>
<body>
<p><input placeholder="Search for a Spanish word" type="">
<p><output></output>
<script src=Dictionary.js></script>
<script>
let es2en = new Dictionary('spanish.json')
console.log(es2en.find('calle')) // 'street'
input.addEventListener('submit', ev => {
ev.preventDefault();
let translation = dictionary.find(ev.target.value);
output.innerHTML = translation;
})
</script>
</body>
</html>
到目前为止,一切都很好。但是,假设我想要子类Dictionary
化并添加一个计算所有单词并将该计数添加到页面的方法。(伙计,我需要一些投资者。)
因此,我获得了另一轮资金并实施CountingDictionary
:
class CountingDictionary extends Dictionary {
constructor(url){
super(url)
}
countEntries(){
return this.entries.length
}
}
新的单页应用程序:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Counting Spanish Dictionary</title>
</head>
<body>
<p><input placeholder="Search for a Spanish word" type="">
<p><output></output>
<script src=Dictionary.js></script>
<script>
let
es2en = new CountingDictionary('spanish.json'),
h1 = document.querySelector('h1'),
input = document.querySelector('input'),
output = document.querySelector('output');
h1.innerHTML = es2en.countEntries();
input.addEventListener('input', ev => {
ev.preventDefault();
let translation = es2en.find(ev.target.value);
if(translation)
output.innerHTML = `${translation}`;
})
</script>
</body>
</html>
当此页面加载时,h1
将填充0
.
我知道我的问题是什么,我只是不知道如何解决它。
问题是fetch
调用返回 a Promise
,并且.entries
只有在 Promise 返回后,该属性才会填充来自 URL 的数据。在那之前,
.entries
仍然是空的。
我怎样才能.countEntries
等待 fetch 承诺解决?
还是有更好的方法来完全实现我想要的?