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

141
Views
Javascript: (implicitely) call a final method after method chains

I'm looking for a way to call a method "implicitely" after a chain (fluent interface pattern).

I already have something like

class Foobar {
  methodA() {
    // update state
    return this;
  }

  methodB() {
    // update state
    return this;
  }

  applyChanges() {
    // persist the state at this point
  }
}

And on the usage:

new Foobar().methodA().methodB().applyChanges();

The thing here, is that I don't know in advance if users of the class will use only one chain method or two (or even zero) and for "developer experience", I didn't want to expose the applyChanges method.

Is there a way to perform that? Or even another pattern I could implement. For example, I thought I could stack the method calls first, but I still won't know when to stop and execute the applyChanges method :(

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

0

If the applyChanges operation were async (and I'm guessing the "persisting" might need something asynchronous anyway), it would be easy: you could have a then method like this:

async applyChanges () { /*...*/ }

then (success, failure) {
  return this.applyChanges().then(success, failure)
}

Then awaiting your object would implicitly apply changes and wait for them to be done (await new Foobar().methodA().methodB()), because async/await uses promises under the hood, so await x will cause x.then to be called if existing. This is how Mongoose query objects behave for example.

about 4 years ago · Juan Pablo Isaza Report

0

Ok so I actually got away with it thanks to Polly. Because it lazily evaluates the http handler i'm building, it gets the "right version" of it when the HTTP requests happen :)

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!