このデータが にあるとします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
}
}
そして、それをインスタンス化し、それを使用して、この小さな単一ページのアプリで「calle」を検索できます。
<!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
呼び出しが を返し、Promise
Promise.entries
が返されたときにのみプロパティに URL からのデータが入力されることです。それまでは、
.entries
空のままです。
.countEntries
fetch promise が解決するのを待つにはどうすればよいですか?
または、ここで私が望むものを完全に達成するためのより良い方法はありますか?