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

279
Visualizações
passing an error from an async helper function to the client

I am writing a NodeJs MVC application using Sequelize. I have 2 models (Model1 and Model2) which are associated in the junction table Models by a ManyToMany relationship.

EXAMPLE

Model1                Model2              Models
             
|id_model| descr |   |id_model| descr |   |mod1_id|mod2_id|
| ------ | ----- |   | ------ | ----- |   | ----- | ----- |
|      1 | some  |   |      1 | thing |   |     1 |     2 |
|      2 | many  |   |      2 | one   |   |     1 |     1 |
                     |      3 | where |

If I want to update Model1.id_model = 1's relationships in the junction table so that

Models
|mod1_id|mod2_id|
| ----- | ----- |
|     1 |     2 |
|     1 |     3 | * instead of 1

In order to DELETE * FROM Models WHERE mod1_id = 1 and INSERT the new relationships (through a checkbox from the View or whatever), I wrote a simple helper function:

// helpers.js
const db = require('../models');
const Models = db.models;

exports.deleteAllRelations = async (id) => {
  const deleted = await Models.destroy({
    where: {mod1_id: id},
    truncate: false
  })
  
};

that I could call from Model1's update function defined in the controller:

// model1.controller.js
const db = require('../models');
const Model1 = db.model1;
const helpers = require('./helpers');

exports.update = async (req, res) => {
  const id = req.params.id;

  // .... missing code .... //

  try {
    // delete all relationships before adding the new ones
    await helpers.deleteAllRelation(id) // <-- CALLING THE HELPER
  }
  catch (e) {
    return res.status(500).send({message: e.message})
  }
  // subscribe student to each selected course
  req.body.models.forEach(async model2 => {
    /* add new relationships */
  })
  return res.status(200).send({message: "Model updated"})
};

QUESTION how should I handle the deleteAllRelations async helper function possible errors and pass them to the client?

Should I wrap the await Models.destroy call into a try/catch block? Should I return a Promise? Could you share an example?

thank you for your help!

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