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

151
Views
Abortar en el constructor

En JavaScript y/o TypeScript, ¿cuál es el enfoque común para resolver el siguiente problema?

Supongamos que tenemos una clase cuyo constructor depende de alguna operación. Si esa operación falla, la instancia no debe crearse.

Ejemplo:

 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? } } }

Las soluciones que se me ocurren incluyen tratar de devolver un objeto vacío o arrojar un error. Pero, ¿hay un enfoque común/preferido?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Personalmente, me gusta tener constructores puros sin efectos secundarios. Simplemente pasa datos y crea su objeto. Es mucho más fácil de usar, probar y depurar.

Y si desea tener un efecto secundario (como validación, obtención de datos), cree una función estática en el objeto que será responsable de eso.

Otra cosa buena es que puede convertir esa función en una función asíncrona sin ningún problema (los constructores no pueden ser asíncronos).

 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 Report
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!