'How can I update the status of a backend job on the frontend using Node Express?
Say I have a shop selling fruits and vegetables, and every time I am adding a new product to my database, I am running a node script that fetches the prices of that product from other shops. For example:
const axios = require('axios');
const db = require('./db')
(async() => {
// The new product I am adding
const time = new Date();
const newProductToAdd = {
slug: 'green-apple',
name: 'Green Apple',
price: 1.25,
created: time,
otherShops: []
};
// The shops to check prices from
const shopsToFetchFrom = [
{name: 'BestFruits', url: 'https://bestfruits.com/api'},
{name: 'GetYourVeg', url: 'https://getyourveg.com/api'},
{name: 'LeanGreen', url: 'https://leanandgreen.com/api'}
];
// Getting the prices from these other shops
await shopsToFetchFrom.reduce(async(promise, shop) => {
await promise;
const res = await axios.get(`${shop.url}/${newProductToAdd.slug}`);
newProductToAdd.otherShops.push({shopName: shop.name, price: res.data.price})
console.log('received price from', shop.name)
}, Promise.resolve())
// Inserting to my database
await db.insertProduct(newProductToAdd)
})()
Every time I want to add a new product, I open the file, I change the params for newProductToAdd, and I then run the script node addProduct.js
Now to make things easier I want to enable my employees to add a new product without having to access any code, with a simple single-page frontend where they can add a product name, slug and price, and upon submitting the form, the request is sent to my express backend, the addProduct.js is executed using the provided params.
My question is - suppose the process of fetching the prices from these other shops takes anywhere between 10 seconds to 2 minutes - is there a way I can update the frontend when the new product is being saved? e.g. "Product is being added, 1/5 shops prices checked, 5/5 shops prices checked, product inserted to db, done".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
