S
S
Spooky 20202020-12-09 18:10:34
Node.js
Spooky 2020, 2020-12-09 18:10:34

What is the best way to write synchronous code in Node (for sequential DB requests)?

It is necessary to sequentially execute several queries to the database, each new query depends on the results of the previous ones.
At one time, I solved this using promises, but it turned out to be so cumbersome and inconvenient that instead of Node, I began
to use Python and php. It's also inconvenient that you can't directly use this inside connection.<methodName>()
Maybe there are more convenient ways now? Tell me where to dig / look. I am attaching a code snippet.

promise hell
ConstructorName.prototype.process = function() {
  const connection = mysql.createConnection({
    host: "-",
    user: "-",
    password: "-",
    database: "-"
  });
  connection.connect();

  new Promise(function (resolve, reject) {
    connection.query("SHOW TABLES", (err, results, fields) => {
      if (err) reject(err);
      results.some(item => (Object.values(item).indexOf('<tablename>') !== - 1)) 
      ? resolve('таблица в порядке')
      : reject(`Таблица с именем ${'name'} не обнаружена`);
    });
  })
  .then(
    result => {
      return new Promise(function (resolve, reject) {
        connection.query(`SHOW COLUMNS FROM  <tablename>`, (err, results, fields) => {
          if (err) reject(err);
          const tableFields = results.map(item => item["Field"]);
          ["<fieldname>", "<fieldname>", "<fieldname>", "<fieldname>"].every(item => tableFields.indexOf(item) !== -1)
          ? resolve('Поля в порядке')
          : reject(`поле с именем ${'<fieldname>'} не обнаружено`);
        })
      })
    },
    error => { console.log(error) }
  )
  // Дальше множество аналогичного кода в .then(тоска-печаль)...
  .finally(
    () => connection.end()
  );
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuriy Vorobyov, 2020-12-13
@spooky_2020

Yes, now there is syntactic sugar in the form of async/await. You can read about it here and here

ConstructorName.prototype.process = async () => {
  const connection = mysql.createConnection({
    host: "-",
    user: "-",
    password: "-",
    database: "-"
  });
  connection.connect();

  const operation = new Promise((resolve, reject) =>  {
    connection.query("SHOW TABLES", (err, results, fields) => {
      if (err) reject(err);
      results.some(item => (Object.values(item).indexOf('<tablename>') !== - 1)) 
      ? resolve('таблица в порядке')
      : reject(`Таблица с именем ${'name'} не обнаружена`);
    });
  });

  try {
    const result = await operation;

    const newOperation = new Promise(function (resolve, reject) {
      connection.query(`SHOW COLUMNS FROM  <tablename>`, (err, results, fields) => {
        if (err) reject(err);
        const tableFields = results.map(item => item["Field"]);
        ["<fieldname>", "<fieldname>", "<fieldname>", "<fieldname>"].every(item => tableFields.indexOf(item) !== -1)
        ? resolve('Поля в порядке')
        : reject(`поле с именем ${'<fieldname>'} не обнаружено`);
      })
    });

    await newOperation;
  } catch (error) {
    console.log(error);
  } finally {
    connection.end();
  }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question