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

314
Views
Can we have more than one async methods within a class in Javascript?

ContatoModel.js =

 class Contato {
      constructor(body) {
        this.body = body;
        this.errors = [];
        this.contato = null;
      };
    
  async register() {
    this.valida();
    if(this.errors.length > 0) return;

    this.contato = await ContatoModel.create(this.body);
  };

  async findId(id) {
    if(typeof id !== 'string') return;
    const user = await ContatoModel.findById(id);
    return user;
  };...

contatoController.js =

 exports.register = async (req,res) => {
  try{
    const contato = new Contato(req.body);
    await contato.register();

    if (contato.errors.length > 0) {
      req.flash('errors', contato.errors);
      req.session.save(() => res.redirect('/contato/'));
      return;
    }

    req.flash('success', 'Contato registrado!');
    req.session.save(() => res.redirect(`/contato/${contato.contato._id}`));
    return;
  }catch(e){
    console.log(e);
    return res.render('404');
  };
};

exports.update = async (req,res) => {
  if(!req.params.id) return res.render('404');
  
  const contato = await Contato.findId(req.params.id)

  if(!contato) return res.render('404');

  res.render('contato', { contato });
  
};

const contato = await Contato.findId(req.params.id) here findId is equal to any

but

await contato.register(); register looks like this: (method) Contato.register(): Promise

My Solution was to put the method outside the class, like this:

Contato.buscaPorId = async function(id) {
  if(typeof id !== 'string') return;
  const user = await ContatoModel.findById(id);
  return user;
}

what did I do wrong?

about 4 years ago · Juan Pablo Isaza
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!