The method getClassesAndSubjects
initiates an asynchronous process, meaning that when you call getClasses
, the operation is still ongoing. It is crucial to return an observable or a promise from getClassesAndSubjects
:
public getClassesAndSubjects(school: number, whenData: string): Observable<your-type> {
const observable = this.classService.GetClassesAndSubjects(school, whenDate);
observable.subscribe(data => {
if (!data.hasOwnProperty('errors')) {
this.classesSubjects = data;
}
}, error => {
console.log("ERROR loading GetClassesAndSubjects: " + error);
});
return observable;
}
Now:
a.getClassesAndSubjects(1,'2018-01-01').subscribe(value => {
a.getClasses();
});
If a function involves asynchronous tasks, any subsequent actions relying on the outcomes of said operations must be patient and wait for them to complete.
You may also opt for using async/await
. Here, the asynchronous function needs to return a Promise
:
public async getClassesAndSubjects(school: number, whenData: string): Promise<your-type> {
const observable = this.classService.GetClassesAndSubjects(school, whenDate);
observable.subscribe(data => {
if (!data.hasOwnProperty('errors')) {
this.classesSubjects = data;
}
}, error => {
console.log("ERROR loading GetClassesAndSubjects: " + error);
});
return observable.toPromise();
}
Then, wherever it's needed:
async function whatever() {
// ...
await a.getClasseandSubjects(1, '2018-01-01');
a.getClasses();
}
By employing this approach, the execution of the function whatever
pauses until the promise derived from a.getClassesAndSubjects
either resolves or rejects, permitting the availability of data when executing a.getClasses
. Although the function appears 'suspended,' the application remains operational as the async function is internally segmented and processed within a Promise.then
structure by the compiler, delivering a refined solution.
It's important to note that any function leveraging await
should be marked with async
.