Asynchronous mysql queries in nodejs

Asked

Viewed 75 times

-1

Hello, I have a code in nodejs with mysql database. on one of the paths referring to the path(path) need to fetch all readings from 3 sensors (each sensor is a table) that have the path field equal to the path id, I used a model of chained predecessors but ended up changing to a model with await like the one below

path.gps = await sql_op.select(null, targets, 'gps')
path.giroscopio = await sql_op.select(null, targets, 'giroscopio')
path.acelerometro = await sql_op.select(null, targets, 'acelerometro')

the search functions in mysql are implemented and work correctly, each of them returns a promisse that solves when the search is completed, my doubt is on how to optimize this query, since I have to make the 3 selects to can display the data on the page

  • Good afternoon, one way to optimize is to create only a select since you share the path field.

1 answer

2


You can cuddle in a array of promises and then use the Promise.all to run them in parallel with the await to await the execution of all:

// ...
const promessas = [
  sql_op.select(null, targets, 'gps'),
  sql_op.select(null, targets, 'giroscopio'),
  sql_op.select(null, targets, 'acelerometro'),
];

const [gps, giroscopio, acelerometro] = await Promise.all(promessas);

path.gps = gps;
path.giroscopio = giroscopio;
path.acelerometro = acelerometro;
// ...

Observing: In that section that was provided this is the only change that comes to mind, but if you provide the implementation of the function sql_op.select I can also try to improve.

Promise.all

The method Promise.all(iterable) returns a promise that solves when all the promises in the iterable argument are resolved.

  • 1

    Thanks, the query itself, I think is well written. I’m using the mysql module with a pool of 10 connections

Browser other questions tagged

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