If I come across code like this in my Ionic/Angular/TypeScript project...
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;
...the arr
will be empty upon return due to the asynchronous nature of the then()
handler not being executed yet.
Is there a way to return the array of strings from within the Promise handler? Currently, all species
objects are stored in memory from the database, but preserving them all may not be ideal as the number could grow significantly.
This code snippet is extracted from an ionic2-autocomplete getResults()
function that is required to return an array of strings directly, rather than another Promise.