Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda