I have a modular JS app using external classes. It communicates with server side API and renders appropriate results. For learning purposes I want it to be pure vanilla JS without any frameworks and key libraries.
index.js
import Project from "./AppStructure/Models/Project.js";
let project;
let projectAPI = await fetch(projectUrl).then(res => res.json());
function onUserCreate() {
project = new Project(projectAPI);
project.loadObject3Ds();
console.log(project);
console.log(project.object3Ds);
console.log(project.object3Ds[0]);
project.object3Ds.forEach(function (object) {
doSomething(object);
});
function onUserUpdate() {
requestAnimationFrame(onUserUpdate);
renderSomething();
}
onUserCreate();
onUserUpdate();
Project.js
export default class Project {
constructor(project) {
this.object3DsIds = project.object3DsIds;
this.object3Ds = new Array();
}
loadObject3Ds() {
let object3Ds = new Array();
this.object3DsIds.forEach(async function (object3DId) {
let object3D = new Object3D();
let objectUrl = 'https://localhost:44555/api/object3Ds/' + object3DId
let object = await fetch(objectUrl).then(res => res.json());
object3D.id = object.id;
object3Ds.push(object3D)
});
this.object3Ds = object3Ds;
}
}
The problem occurs when app is doing the forEach loop - simply nothing happens. It seems that it's initialised before object3Ds are pushed to project.object3Ds array.
When I console log project it seems to be complete but project.object3Ds array is a bit weird (preview is [], expanded is ok) and project.object3Ds[0] logs as undefined.
Why doesn't forEach loop wait for loadObject3Ds() method to be executed first? What am I doing wrong? Thank you for help.