Categories
JavaScript Answers

How to make synchronous database queries with Node.js?

Spread the love

To make synchronous database queries with Node.js, we use the synchronize module.

For instance, we write

const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const sync = require("synchronize");

const db = mysql.createConnection({
  host: "localhost",
  user: "user",
  password: "password",
  database: "database",
});

db.connect((err) => {
  if (err) {
    console.error("error connecting: " + err.stack);
    return;
  }

  const save = async () => {
    const post = { id: newId };
    const query = sync.await(
      db.query("INSERT INTO mainTable SET ?", post, sync.defer())
    );
    const newId = query.insertId;
    const post = { foreignKey: newId };
    db.query("INSERT INTO subTable SET ?", post, (err, result) => {
      if (err) {
        throw err;
      }
    });
  };
});

to define the save function.

In it, we call sync.await to wait for the query to finish before we move to the next line of code.

We have the save function in the connect callback so we only make queries when the connection is established.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.