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

152
Views
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 answers
Answer question

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