How can I update the frontend after waiting for the database in the backend to update in Node.js/Express?

I saw a similar question posted Here, but they are using MEAN-Stack.

I am currently just using a ‘setTimeout’ function to wait a few seconds before requesting new data from the server using a fetch api to give it time to update but this doesnt feel like the right way to do it. Is there a simple way for the front-end to update only after the database is updated in Express? I am new to Node please forgive me.

app.js:

const express = require('express'); const app = express(); const mysql = require('mysql');   let viewData = {     //html data }  var pool = mysql.createPool({     connectionLimit : 10,     host: "localhost",     port: 3306,     database: 'testing',     user: "root",     password: "pass" });  function sql(type) {      if(type == 'select') {      //Select query here     }     if(request == 'addRow') {      //Insert query here     } }  app.get(`/`, function (req, res) {     res.sendFile('./views/index.html', {root: __dirname}); })  app.post('/api/add', function(req, res){     res.setHeader('Content-Type', 'application/json');     sql('addRow') });  app.get('/api/viewData', function (req, res) {     res.setHeader('Content-Type', 'application/json');     res.send(JSON.stringify(viewData)); }) 

index.js:

function loadData() {       fetch('/api/viewData')       .then(z => z.json())       .then(a => {         //update html       }) }  function postData(a) {     fetch('/api/add', {       method: 'POST',       headers: {         'Content-Type': 'application/json'       },         body: JSON.stringify({           //data to send to app.js       })     }).then(setTimeout(function(){loadData();}, 3000))   }  
Add Comment
1 Answer(s)

You should use async and await function

Example: After async/await

async function fun1(req, res){   let response = await request.get('http://localhost:3000');     if (response.err) { console.log('error');}     else { console.log('fetched response'); } 

The complete code of our example is shown below:

npm install express jsonschema body-parser promise-mysql

var express = require('express'); var bodyParser = require('body-parser') var app = express(); var validate = require('./validate') var mysqlConnection = require('./connectionShare'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json());  const addItem = function(item, connection){  console.log("Adding Item");  return new Promise(function(resolve, reject){   connection.query("INSERT INTO product SET ?", item)   .then(function(result){    resolve(item.seller);   }).catch(function(error){    reject(error);   });  }) }  const findOrCreateUser = function(user,connection){  console.log("Finding User");  return new Promise(function(resolve,reject){   connection.query("SELECT * FROM user WHERE email=" + connection.escape(user.email))    .then(function(results){     if(results.length == 1){      resolve(results[0].id)     } else {      connection.query("INSERT INTO user SET ?", user)      .then(function(results){       resolve(results.insertId);      });     }    }).catch(function(error){     reject(error);    })  }) }  const selectUserItems = function(userID,connection){  console.log("Selecting Items " + userID);  return new Promise(function(resolve,reject){   connection.query("SELECT * FROM product WHERE seller = " + connection.escape(userID))    .then(function(results){     resolve(results);    }).catch(function(error){     reject(error);return;    });   }) }  app.post('/add/product', validate.JsonValidation, mysqlConnection.getConnection, async function(req,res){  var connection = req.connection;  var item = {   name: req.body.name,   price: req.body.price,   width: req.body.width,   height: req.body.height,   added: req.body.added,   image: req.body.image  };   var user = {   username: req.body.seller.username,   email: req.body.seller.email,   votes: req.body.seller.votes  };   try {   item.seller = await findOrCreateUser(user,connection);   var user_id = await addItem(item,connection);   var items = await selectUserItems(user_id, connection);   connection.connection.release();   res.status(200).json(result);  } catch(error) {   res.status(500).end(error);  } });  process.on('uncaughtException', error => console.error('Uncaught exception: ', error)); process.on('unhandledRejection', error => {console.error('Unhandled rejection: ', error));  app.listen(8000, function () {  console.log('App listening on port 8000') }); 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.