3

假设我有这些数据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 承诺解决?

还是有更好的方法来完全实现我想要的?

4

3 回答 3

5

问题是fetch调用返回 a Promise,并且.entries只有在 Promise 返回后,该属性才会填充来自 URL 的数据。在那之前, .entries仍然是空的。

你需要做出entries承诺。这样,您的所有方法都必须返回 Promise,但Dictionary实例可以立即使用。

class Dictionary {
  constructor(url) {
    this.entriesPromise = fetch(url)
      .then(response => response.json())
  }
  find(query) {
    return this.entriesPromise.then(entries => {
       var entry = entries.find(e => e.word == query);
       return entry && entry.translation;
    });
  }
}
class CountingDictionary extends Dictionary {
  countEntries() {
    return this.entriesPromise.then(entries => entries.length);
  }
}

let es2en = new CountingDictionary('spanish.json'),
    h1 = document.querySelector('h1'),
    input = document.querySelector('input'),
    output = document.querySelector('output');

es2en.countEntries().then(len => {
  fh1.innerHTML = len;
});
input.addEventListener(ev => {
  ev.preventDefault();
  es2en.find(ev.target.value).then(translation => {
    if (translation)
      output.innerHTML = translation;
  });
});

还是有更好的方法来完全实现我想要的?

是的。看看让构造函数返回 Promise 是不是不好的做法?.

class Dictionary {
  constructor(entries) {
    this.entries = entries;
  }  
  static load(url) {
    return fetch(url)
      .then(response => response.json())
      .then(entries => new this(entries));
  }

  find(query) {
    var entry = this.entries.find(e => e.word == query);
    return entry && entry.translation;
  }
}
class CountingDictionary extends Dictionary {
  countEntries() {
    return this.entries.length;
  }
}

let es2enPromise = CountingDictionary.load('spanish.json'),
    h1 = document.querySelector('h1'),
    input = document.querySelector('input'),
    output = document.querySelector('output');

es2enPromise.then(es2en => {
  fh1.innerHTML = es2en.countEntries();
  input.addEventListener(…);
});

如您所见,与包含 Promise 的实例相比,这种方法需要更少的整体嵌套。此外,该实例的 Promise 具有更好的可组合性,例如,当您需要在安装侦听器和显示输出之前等待 domready 时,您将能够获得 DOM 的 Promise 并可以等待两者都使用Promise.all.

于 2016-09-08T15:36:08.353 回答
0

您必须将fetch()调用结果分配给某个变量,例如:

initialize(){
  this.promise = fetch(this.url)
    .then(response => response.json())
    .then(entries => this.entries = entries)
}

然后你可以调用then()它的方法:

let es2en = new CountingDictionary('spanish.json'),
    h1 = document.querySelector('h1'),
    input = document.querySelector('input'),
    output = document.querySelector('output');

es2en.promise.then(() => h1.innerHTML = es2en.countEntries())

input.addEventListener('input', ev => {
  ev.preventDefault();
  let translation = es2en.find(ev.target.value);
  if(translation)
    output.innerHTML = `${translation}`;
})
于 2016-09-08T15:36:00.393 回答
0

一个简单的解决方案:在你做之后保持承诺fetch(),然后添加一个ready()方法让你等到类完全初始化:

class Dictionary {
  constructor(url){
    /* ... */

    // store the promise from initialize() [see below]
    // in an internal variable
    this.promiseReady = this.initialize();
  }

  ready() {
    return this.promiseReady;
  }

  initialize() {
    // let initialize return the promise from fetch
    // so we know when it's completed
    return fetch(this.url)
      .then(response => response.json())
      .then(entries => this.entries = entries)
  }

  find(query) { /* ... */ }
}

然后,您只需.ready()在构建对象后调用,您就会知道它何时加载:

let es2en = new CountingDictionary('spanish.json')
es2en.ready()
  .then(() => {
    // we're loaded and ready
    h1.innerHTML = es2en.countEntries();
  })
  .catch((error) => {
    // whoops, something went wrong
  });

作为一个额外的优势,您可以只使用它.catch来检测加载过程中发生的错误,例如网络错误或未捕获的异常。

于 2016-09-08T15:38:32.317 回答