Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

214
Vistas
How to get a JavaScript class method to wait to return data until data in the constructor is loaded?

How do I get the list() method to wait for the data to be loaded in the constructor before it resolves its promise back to the caller?

import fetch from 'node-fetch';

class Employees {
    constructor() {
        if (Employees._instance) {
            return Employees._instance
        }
        Employees._instance = this;

        this.employees = [];
        this.dataLoaded = false;

        this.url = 'https://raw.githubusercontent.com/graphql-compose/graphql-compose-examples/master/examples/northwind/data/json/employees.json';

        (async () => {
            const response = await fetch(this.url);
            this.employees = await response.json();
            this.dataLoaded = true;
            console.log(`work done: got ${this.employees.length} employees`);
        })();
    }

    list() {
        return new Promise((resolve) => {
            resolve(this.employees.map(m => `${m.firstName} ${m.lastName} (${m.id})`));
        });
    }

}

const employees = new Employees();

(async () => {
    console.log(await employees.list());
})();
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I recommend having the constructor save the promise from the data loading onto this, and then list can await that promise:

class Employees() {
  constructor() {
    if (Employees._instance) {
      return Employees._instance
    }
    Employees._instance = this;

    this.employees = [];
    this.dataLoaded = false;

    this.url = 'https://raw.githubusercontent.com/graphql-compose/graphql-compose-examples/master/examples/northwind/data/json/employees.json';
    
    this.initPromise = (async () => {
      const response = await fetch(this.url);
      this.employees = await response.json();
      this.dataLoaded = true;
      console.log(`work done: got ${this.employees.length} employees`);
    })();
  }

  async list() {
    await this.initPromise;
    return this.employees.map(m => `${m.firstName} ${m.lastName} (${m.id})`));
  }
}

If the load hasn't finished yet, then the await will cause list to wait however long is necessary. If loading has finished, then initPromise is in a resolved state, and list will resume more or less immediately (when the microtask queue executes).

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use a Deferred object.

a deferred represents work that is not yet finished

// fetch mock with 3 seconds wait
fetch = () => {
     return new Promise((resolve) => {
         setTimeout(() => {
             resolve({
                 json: () => new Promise((r) => r([
                        {firstName: 'Arthur', lastName: 'Pym', id: 1},
                        {firstName: 'August', lastName: 'Barnard', id: 2},
                        {firstName: 'M.', lastName: 'Poe', id: 3}
                 ]))
             });
         }, 3000);
     });
}

class MyDeferred {
    resolve = null;
    reject = null;
    promise = null;
    constructor() {
        this.promise = new Promise((res, rej) => {
            this.resolve = res;
            this.reject = rej;
        });
    }
}

class Employees {
    deferred = new MyDeferred();
    constructor() {
        if (Employees._instance) {
            return Employees._instance
        }
        Employees._instance = this;

        this.employees = [];
        this.dataLoaded = false;

        this.url = 'https://raw.githubusercontent.com/graphql-compose/graphql-compose-examples/master/examples/northwind/data/json/employees.json';

        (async () => {
            const response = await fetch(this.url);
            this.employees = await response.json();
            this.dataLoaded = true;
            this.deferred.resolve();
            console.log(`work done: got ${this.employees.length} employees`);
        })();
    }

    list() {
        return new Promise((resolve) => {
            this.deferred.promise.then(() => {
                resolve(this.employees.map(m => `${m.firstName} ${m.lastName} (${m.id})`));
            });
        });
    }

}

const employees = new Employees();

(async () => {
    console.log(await employees.list());
})();

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda