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

150
Vistas
Abort in constructor

In JavaScript and/or TypeScript, what is the common approach to solving the following problem?

Assume we have a class whose constructor depends on some operation. If that operation fails, the instance should not be created.

Example:

class Item {

    constructor(itemId) {

        // Try to get the data for the passed-in item id
        const itemData = itemDataMap.get(itemId);

        // If the item data was found
        if (itemData) {
            // Great, continue to init the instance as normal...
        }
        else {
            // Problem: We can't init the instance without the item data.
            // Hence we don't want to return an instance.
            // What should we do here?
        }
    }
}

Solutions I can think of include trying to return an empty object, or throwing an error. But is there a common/preferred approach?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Personally I like having pure constructors without any side-effects. You just pass data and it creates you object. It so much easier to use, test and debug.

And if you wish to have side-effect (like validation, data fetching), create static function on the object that will be responsible for that.

One more nice thing is that you can convert that function to async function without any issue (constructors can't be async).

class Item {
  constructor(data) {
    //...
  }

  static create(id) {
    if (id === 1) {
      throw new Error("my error")
    }
    return new Item({
      id
    })
  }
}


console.log(Item.create(2))
console.log(Item.create(1))

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