I’ve recently started working on an Ionic 4 project, delving into the realms of Javascript / Typescript for the first time. Understanding async / await / promise seems to be a bit challenging for me.
Here’s the scenario:
In one of the pages of my app (let’s refer to it as tab1.page.ts ), there's a function that calls a service function:
Get_Sim_Agents() {
this.simConfig.Get_Sim_Agents();
}
Now, in the service page, here’s the function (a basic http get function):
/**
* Fetch the datas in order to populate the app
*/
Get_Sim_Agents(){
this.http.get(
"http://" +
this.ip_address +
":" +
this.port +
"/get_datas"
).subscribe(response => {
var data = JSON.stringify(response, null, 2);
try {
var obj = JSON.parse(data);
// Here I manipulate the retrieved data
});
} catch (e) {
console.log(e);
}
});
}
Currently, everything works just fine. However, I wish for the service function to return the treated data as a string. But figuring out the correct syntax has been quite a challenge for me. Here’s what I’ve attempted:
In the service:
/**
* Fetch the Sim_Agents from the Simulation_orchestrator in order to populate the app
*/
async Get_Sim_Agents() : Promise<string>{
this.http.get(
"http://" +
this.simulation_orchestrator_ip_address +
":" +
this.simulation_orchestrator_port +
"/get_sim_agents"
).subscribe(response => {
var data = JSON.stringify(response, null, 2);
// Perform some actions on the data
return JSON.parse(data);
});
return 'test';
}
And on the page:
Get_Sim_Agents() {
this.simConfig.Get_Sim_Agents().then((result) => {console.log(result)});
}
With this code snippet, my function called on the page immediately returns ‘test’. What I actually desire is for it to wait until the http response is received. I’ve tried various syntaxes but haven’t been able to achieve the desired outcome 🤔
Just to make things clear:
What I’m aiming for is:
1/ The page triggers the service function 2/ The service sends the request and receives a response 3/ The service performs necessary operations (like populating the app with the data) 4/ Subsequently, it returns a string back to the page, saying “job is done”
But so far, all I’ve found are solutions that directly send the response from the service to the page without any pre-treatment by the service