My getData function makes an api call, then puts each returned object into an array. The array is then returned. I now need my processData function to await the results from the getData function and then further process it. Currently I dont get any results when I console.log(cleaningData)What am I doing wrong with async/await? What am I missing?
getData() {
var dataBucket = []
this.https.get('https:******FAKEURL*******').subscribe((response: any) => {
console.log(response.data)
for(let i = 0 ; i < response.data.length ; i++) {
dataBucket.push(response.data[i])
}
});
console.log(dataBucket);
return dataBucket;
}
async processData() {
let cleaningData = await this.getData();
console.log(cleaningData);
//do something with cleaningData
}
Advertisement
Answer
In angular you normally follow another logic for async functions. You declare what should happen when an asynchronous function returns with a subscription. So what should happen when it returns start from your subscription block of code (not from somewhere else where you wait for your asunchronous function)
getData() {
this.https.get('https:******FAKEURL*******').subscribe((response: any) => {
var dataBucket = [] <-----this should be here declared
console.log(response.data)
for(let i = 0 ; i < response.data.length ; i++){
dataBucket.push(response.data[i])
}
this.processData(response) <-------you call that here
});
}
processData(response: any){ <-----you don't need async and await
// <----- here you can do anything with the response from getData()
console.log(cleaningData);
//do something with cleaningData
}