Adonisjs, how to update multiple tables with just one await?

Asked

Viewed 309 times

0

I’m learning to work with Adonisjs and I found several ways to update, but I always like the most performative way, after reading several articles and the documentation came to the following code:

async update ({ params, request }) {
    const dados_aluno = request.only(['nome','cpf','dt_nascimento','peso',
                                      'altura','sexo_id','tipo_sanguineo_id'])
    const dados_endereco = request.only(['cep','endereco','numero','bairro','cidade','uf'])
    const dados_contato = request.only(['email','telefone','celular'])
    await Database.table('alunos').where('id', params.id).update(dados_aluno)
    await Database.table('enderecos').where('aluno_id', params.id).update(dados_endereco)
    await Database.table('contatoes').where('aluno_id', params.id).update(dados_contato)
}

It works, but I would like to make the three updates with a await only, it is possible?

1 answer

2

I don’t know Donis, giving another generic answer...

Recalling that what the await does is "unwind" the response of an object of type Promise<T>.

const x = await y  //onde y possui tipo Promise<Algo>
// x possuirá o tipo "Algo"

The code below does practically the same thing, only without the syntax of await.

y.then( x => {
  console.log(x)
})

When a Promise is finished and gives its result in "then", it is said that it "solved" or "rejected" (in case of error).

The function Promise.all receives an array of Promises and returns a new Promise that is only settled after all previous entries have been solved. It can be used to call things in "parallel". It returns in your . then an array of incoming replies.

[Promise<X>, Promise<Y>, Promise<Z>] --> Promise.all --> Promise<[ X, Y, Z ]>

Then you’d write something like

await Promise.all([
  Database.table(...),
  Database.table(...),
  Database.table(...)
])

Now here’s an observation. If this data of yours has a database relationship (for example, if the address you want to add belongs to the student), Adonis may have some syntax for inserting objects related to a single command, as it is a common feature in Orms.

  • Yes there is a relationship and I managed to do in a single await o select all e create but the update I haven’t found yet, but I will continue studying the framework because it is beautiful. I really don’t know so much about Promises and I’ll study more about them, thanks for the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.