返回一个字符串数组 - 在Promise处理程序中填充的数组

时间:2017-11-09 18:18:02

标签: angular typescript ionic-framework promise

所以,如果我在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()处理程序尚未执行。

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

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

1 个答案:

答案 0 :(得分:0)

您需要将a返回到调用异步函数的位置。你必须返回一个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;
});