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, 'turing_tasks', 'products.json')
const customersFile = path.join(__dirname, 'turing_tasks', 'customers.json')
const reviewsFile = path.join(__dirname, 'turing_tasks', 'reviews.json')
const imagesFile = path.join(__dirname, 'turing_tasks', 'images.json')
const { products } = JSON.parse(await fs.readFile(productsFile, 'utf-8'))
const product = products.filter(product => product.id === id)[0]
const {reviews} = JSON.parse(await fs.readFile(reviewsFile, 'utf-8'))
const {customers} = JSON.parse(await fs.readFile(customersFile, 'utf-8'))
const {images} = JSON.parse(await fs.readFile(imagesFile, 'utf-8'))
const reviewsData = []
reviews.forEach((review) => {
customer = customers.filter(customer => customer.id === review.customer_id)
if(customer) customer = customer[0]
const reviewImages = images.filter(image => review.images.includes(image.id))
reviewsData.push({
"id": review.id,
"rating": review.rating,
"customer": customer,
"images": reviewImages
})
})
return {
"id": product.id,
"name": product.name,
"reviews": reviewsData
}
}
(async () => {
const result = await getProductDetailByProductID(1);
return result
})(); // 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.