Reputation: 25
I found that when I tried to call functions initializeItems() need to be called first. but checkList() is getting called before initializeItems()
initializeItems() {
this.dataService.readLocalData().subscribe( data => {
console.log('Local Data');
this.items = data;
// console.log(this.items);
this.tempItems = [];
for (const i of this.items.material ){
console.log(i['material-name']);
this.tempItems.push( i['material-name'] );
}
console.log('***********************************************');
console.log(this.tempItems);
});
}
checkList(ev: any){
// set val to the value of the searchbar
const val = ev.target.value;
console.log(val);
console.log(this.tempItems);
// if the value is an empty string don't filter the items
if (val && val.trim() !== '') {
this.tempItems = this.tempItems.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
});
}
}
async getItems(ev: any) {
// Reset items back to all of the items
await this.initializeItems(); //This need to execute first
await this.checkList(ev); //But this getting executed
}
If the function calls sequentially. My result will be
initializeItems()
variable tempItems will be//full list
then
checkList()
variable tempItems will be //filtered list from a searchable drop-down
Upvotes: 0
Views: 34
Reputation: 84902
await
is meant for use with promises. Since initializeItems doesn't return a promise, await doesn't actually wait for anything. You need to modify initializeItems to return a promise. My guess is that you expect the subscribe callback to be invoked exactly once, and at that point the promise should resolve, so you'd want to do this:
initializeItems() {
return new Promise((resolve) => { // <---- creating a promise
this.dataService.readLocalData().subscribe( data => {
console.log('Local Data');
this.items = data;
// console.log(this.items);
this.tempItems = [];
for (const i of this.items.material ){
console.log(i['material-name']);
this.tempItems.push( i['material-name'] );
}
console.log('***********************************************');
console.log(this.tempItems);
resolve(); // <-- resolving the promise
});
}
}
Upvotes: 1