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

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

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 Relatório

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