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?
JavaScript
x
19
19
1
getData() {
2
var dataBucket = []
3
this.https.get('https:******FAKEURL*******').subscribe((response: any) => {
4
console.log(response.data)
5
for(let i = 0 ; i < response.data.length ; i++) {
6
dataBucket.push(response.data[i])
7
}
8
});
9
console.log(dataBucket);
10
return dataBucket;
11
}
12
13
async processData() {
14
let cleaningData = await this.getData();
15
console.log(cleaningData);
16
//do something with cleaningData
17
}
18
19
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)
JavaScript
1
26
26
1
getData() {
2
3
this.https.get('https:******FAKEURL*******').subscribe((response: any) => {
4
5
var dataBucket = [] <-----this should be here declared
6
7
console.log(response.data)
8
9
for(let i = 0 ; i < response.data.length ; i++){
10
11
dataBucket.push(response.data[i])
12
}
13
14
this.processData(response) <-------you call that here
15
});
16
}
17
18
processData(response: any){ <-----you don't need async and await
19
20
// <----- here you can do anything with the response from getData()
21
22
console.log(cleaningData);
23
24
//do something with cleaningData
25
}
26