Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
How to make javascript async method of external class work?

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!