【问题标题】:Returning an array of strings - array populated in Promise handler返回一个字符串数组 - 在 Promise 处理程序中填充的数组
【发布时间】:2018-04-22 20:46:52
【问题描述】:

所以,如果我的 Ionic/Angular/TypeScript 项目中有这样的代码...

let arr: Array<string> = [];
this.databaseProvider.getAllSpecies().then(allSpecies => {
  for(let species of allSpecies) {
    if(species.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1
        || species.latinName.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
      arr.push(species.name + " - " + species.latinName);
    }
  }
});
return arr;

...arr,当然返回的时候会为空,因为then()这个handler还没有被执行。

有没有办法从 Promise 处理程序返回字符串数组?目前,我已将所有 species 对象从数据库加载到内存中,但我不想那样做,因为会有数百个。

代码是来自ionic2-autocompletegetResults()函数的sn-p,它必须返回一个字符串数组,即不是另一个Promise。

【问题讨论】:

  • ionic2-autocomplete 文档声明getResults 被允许返回一个承诺(或可观察的,或常规值)。
  • 我刚刚注意到同样的事情,但由于某种原因,这似乎不适用于我的应用程序。

标签: angular typescript ionic-framework promise


【解决方案1】:

您需要将 a return 放在调用异步函数的位置。你必须返回一个 Promise 或一个 Observable。它是异步的,所以你必须处理这个现实:

return this.databaseProvider.getAllSpecies().then(allSpecies => {  <-- Notice "return"

  let arr: Array<string> = [];
  for(let species of allSpecies) {
    if(species.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1
        || species.latinName.toLowerCase().indexOf(keyword.toLowerCase()) > -1) 
    {
      arr.push(species.name + " - " + species.latinName);
    }
  }
  return arr;
});

【讨论】:

  • 我通过将返回的 Promise 转换为 Observable 来使其工作,如下所示:return Observable.from(this.databaseProvider.getAllSpecies().then(allSpecies =&gt; { ... return arr; }));
猜你喜欢
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 2017-07-08
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多