Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Node.JS Is there a better way to write this JS which is dependent on a Promise?

TheShanachie

New Coder
In a current JS web application. I am currently rendering my pages with specific information from a MongoDB Atlas cluster. Unfortunately, I don't know enough about JS to fix a major issue. The current code queries the Database each time a page is rendered as far as I understand. This seems like a major issue for the speed of my app. I would like understand how these queries can be called and cached at the beginning of the web app so this doesn't have to happen again.

Code:
const express = require('express');
const Link = require('./models/link');
const Site = require('./models/site');
const app = express();
const port = 3000;

const dbURI = 'censored';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then((result) => app.listen(port))
  .catch((err) => console.log(err))
const db = mongoose.connection;

app.set('view engine', 'ejs');
app.use(express.static('public'));

app.get('/', async (req, res) => {
  try {
    const [links, sites] = await Promise.all([
    Link.find({}).sort({ order_no: 'asc' }),
    Site.find({}).sort({ order_no: 'asc' })]);
    res.render('index', { title: "Home", links, sites })
  } catch (e) {
    console.log(e);
    res.sendStatus(500);
  }
});

app.get('/page01', async (req, res) => {
  try {
    const [links, sites] = await Promise.all([
    Link.find({}).sort({ order_no: 'asc' }),
    Site.find({}).sort({ order_no: 'asc' })]);
    res.render('page01', { title: "Home", links, sites })
  } catch (e) {
    console.log(e);
    res.sendStatus(500);
  }
});

app.get('/page02', async (req, res) => {
  try {
    const [links, sites] = await Promise.all([
    Link.find({}).sort({ order_no: 'asc' }),
    Site.find({}).sort({ order_no: 'asc' })]);
    res.render('page02', { title: "Home", links, sites })
  } catch (e) {
    console.log(e);
    res.sendStatus(500);
  }
});
 
Hey there! 🌟

I completely get where you're coming from. It does seem that the database is being queried each time one of your routes is accessed. Caching this data at the beginning would indeed reduce the load on your database, speeding things up! 🚀

Let's refactor your code so that the queries are made just once and the results are stored. Then, you can serve them up as needed without hitting the database again.

JavaScript:
const express = require('express');
const Link = require('./models/link');
const Site = require('./models/site');
const app = express();
const port = 3000;

const dbURI = 'censored';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then((result) => app.listen(port))
  .catch((err) => console.log(err));
const db = mongoose.connection;

app.set('view engine', 'ejs');
app.use(express.static('public'));

let cachedLinks = null;
let cachedSites = null;

const fetchData = async () => {
  try {
    [cachedLinks, cachedSites] = await Promise.all([
      Link.find({}).sort({ order_no: 'asc' }),
      Site.find({}).sort({ order_no: 'asc' })
    ]);
  } catch (e) {
    console.log(e);
  }
};

// Fetch the data right after the server starts
fetchData();

app.get('/', (req, res) => {
  res.render('index', { title: "Home", links: cachedLinks, sites: cachedSites });
});

app.get('/page01', (req, res) => {
  res.render('page01', { title: "Page 01", links: cachedLinks, sites: cachedSites });
});

app.get('/page02', (req, res) => {
  res.render('page02', { title: "Page 02", links: cachedLinks, sites: cachedSites });
});

Remember that while this will speed things up initially, if your database content changes, the cached data won't update automatically. You'd need some strategy for periodically refreshing this cache or doing so upon certain events. But for now, this should give you a nice boost! 😊

Hope this clears things up a bit! Happy coding! 🎉
 
One way to improve JavaScript code dependent on a Promise is by utilizing async/await syntax. This allows for more readable and concise code by avoiding nested Promise chains. Instead, async functions can await the resolution of Promises sequentially. This enhances code readability and simplifies error handling. For more in-depth discussions and examples, you can explore related threads on Quora.
 

New Threads

Buy us a coffee!

Back
Top Bottom