I am new to Javascript. I am trying to read a few files and construct a JSON object response. I am able to run the entire code, however, one last piece is remaining, I am not getting a response from the async function.
const path = require('path')
const fs = require('fs/promises');
const getProductDetailByProductID = async (id) =>{
const productsFile = path.join(__dirname, 'tasks', 'products.json')
const customersFile = path.join(__dirname, 'tasks', 'customers.json')
const reviewsFile = path.join(__dirname, 'tasks', 'reviews.json')
const imagesFile = path.join(__dirname, 'tasks', 'images.json')
const product = await fs.readFile(productsFile, 'utf-8').then(res => {
const data = JSON.parse(res)["products"].filter(product => product.id === id)
return data[0]
})
const response = await fs.readFile(reviewsFile, 'utf-8')
.then(allReviews => {
return JSON.parse(allReviews)["reviews"].filter(review => review.product_id === product.id)
})
.then(async (productReviews) => {
const reviewsData = []
for (const review of productReviews) {
let customer = await fs.readFile(customersFile, 'utf-8').then(res => {
return JSON.parse(res)["customers"].filter(customer => customer.id === review.customer_id)
})
if(customer) customer = customer[0]
const images = await fs.readFile(imagesFile, 'utf-8').then(res => {
return JSON.parse(res)["images"].filter(image => review.images.includes(image.id))
})
reviewsData.push ({
"id": review.id,
"rating": review.rating,
"customer": customer,
"images": images
})
}
return reviewsData
})
.then(reviewsData => {
return {
"id": product.id,
"name": product.name,
"reviews": reviewsData
}
})
console.log(response) // This is working
return response
}
getProductDetailByProductID(1) // This does not fetch anything
I am running this file using below command
nodemon task.js
Also, please recommend a better way of writing this code if it is poorly written. Please share a link for the same.