Functions that return the previous value of a nodejs typescript variable

I hope you can help me, I have these routes that, when making requests to their routes, return the previous value of the request and if I make the request again, it just shows me the data I requested.

import { BaseProduct, Product } from "./product.interface";
import { Products } from "./products.interface"
import { db } from "../db"
/**
 * query Store
 */


 let products: Products 
/**
 * Service Methods
 */
 export const findAll = async (): Promise<Product[]> => {
   
     db.query('SELECT * FROM bsale_test.product;',(err,results)=>{
      products=Object.values(results)
     })
    return Object.values(products)
};

 export const find = async (id: number): Promise<Product> => {
   db.query(`SELECT * FROM bsale_test.product where id=${id};`,(err,result)=>{
    products=Object.values(result)
   })
  return products[0]
};

because when you make the request GET http://localhost:3000/api/products/109 It shows me the data of the previous request and if I make the request again it just shows me the data of the request.

{
  "id": 108,
  "name": "PISCO",
  "url_image": "https://dojiw2m9tvv09.cloudfront.net/11132/product/alto8532.jpg",
  "price": 790,
  "discount": 10,
  "category": 2
}

what would be the following

{
  "id": 109,
  "name": "PISCO ",
  "url_image": "https://dojiw2m9tvv09.cloudfront.net/11132/product/alto408581.jpg",
  "price": 5990,
  "discount": 0,
  "category": 2
}

my routes

// GET products
productsRouter.get("/", async (req: Request, res: Response) => {
    try {
      const products: Product[] = await productService.findAll();
  
      res.status(200).send(products);
    } catch (e:any) {
      res.status(500).send(e.message);
    }
  });
// GET products/:id
productsRouter.get("/:id", async (req: Request, res: Response) => {
    const id: number = parseInt(req.params.id, 10);
  
    try {
      const product: Product = await productService.find(id);
  
      if (product) {
        console.log(product)
        return res.status(200).send(product);
      }
      
      res.status(404).send("product not found");
    } catch (e:any) {
      res.status(500).send(e.message);
    }
  });

Upvotes: 0

Views: 434

Answers (1)

Guille Sanchez
Guille Sanchez

Reputation: 241

Problem is that you are returning the value before computing it, thus, you are returning the previous computed value. See the code you have:

 export const findAll = async (): Promise<Product[]> => {

     db.query('SELECT * FROM bsale_test.product;',(err,results)=>{
         products=Object.values(results) // You are assigning the values of products once the db.query completes
     })
    return Object.values(products) // you are returning the value of product instantly, since you are not waiting for db query to finish
};

Instead, you should return a couple of Promises. This way, you will return the value you want once the callback of the db.query() is called, after the method is completed.

Try with the following code for your methods:

export const findAll = async (): Promise<Product[]> => {
    return new Promise<Product[]>((resolve, reject) => {
        db.query('SELECT * FROM bsale_test.product;', (err, results) => {
            if (err) {
                reject(err)
            } else {
                resolve(Object.values(results))
    
            }
        })
    })
};

export const find = async (id: number): Promise<Product> => {
    return new Promise<Product>((resolve, reject) => {
        db.query(`SELECT * FROM bsale_test.product where id=${id};`,(err, result) => {
            if (err) {
                reject(err)
            } else {
                resolve(Object.values(result))
            }
        })
    }
}

Upvotes: 1

Related Questions