I want to set a Class property by ajax. That code works for me:
class SweetCalendar{
constructor(){
this.getEmployees();
}
getEmployees(){
let url = window.location.protocol + "//" + window.location.host + '/api/v1/employeelist/';
$.ajax({
type: "GET",
url: url,
context: this,
success: function (result, status, xhr) {
this.employees = result;
},
timeout: 120000,
});
}
When I test the class with
var a = new SweetCalendar()
console.log(a.employees)
I receive the expected array of employees. Now I want to iterate over this property with the test-function within the class:
class SweetCalendar{
constructor(){
this.getEmployees();
}
test(){
for(i of this.employees){
console.log(i)
}
}
getEmployees(){
let url = window.location.protocol + "//" + window.location.host + '/api/v1/employeelist/';
$.ajax({
type: "GET",
url: url,
context: this,
success: function (result, status, xhr) {
this.employees = result;
},
timeout: 120000,
});
}
var a = new SweetCalendar();
a.test();
This doesn't work. This.employees is undefined. I assume this is due to the asynchronus ajax but i dont know how to solve this. Have anybody faced this problem as well before?