Reputation: 589
My previous codes don't have a problem rendering HTML. I use just one fetch(). This time when it seems that I need to have two fetches, the first fetch will get just a product ID(coming from the user's cart) that I will use for the second fetch that will take the product details from the product collection.
Those IDs in the first fetch are in an array that's why I used map() to iterate through it while pulling up the product details for each product ID(through the 2nd fetch).
I thought this was going to work, but it seems I cannot get the return value for the map(), my innnerHTML doesn't output at all.
I'm fairly new to programming, if someone can help I would prefer an easy-to-understand method. Or just almost the same as my method I would prefer that or if you can just point out what I'm doing wrong or missing here with my code. Because as a beginner and based on my previous projects this logic is what I came up with, and I'd like to somehow make this work so as to be consistent at the moment.
fetch(`${rootUrl}api/users/getCartItems`,{
method: "GET",
headers:{
"Authorization": `Bearer ${token}`
}
})
.then(result=>result.json())
.then(result=>{
let cartItems = result.itemsArr.map(e=>{
fetch(`${rootUrl}api/products/${e.item}`,{
method: "GET"
})
.then(product=> product.json())
.then(product =>{
return `
<br><br>
${e.item}<br>
${product.name}<br>
${product.description}<br>
${product.price}<br>
<br><br>
`
})
}).join(" ")
content2 = document.querySelector('#content2');
content2.innerHTML = cartItems;
})
Upvotes: 0
Views: 286
Reputation: 2189
Your code is very hard to read. You might find it easier to understand promises using async/await than promise chaining with then, I have converted some of your code to use async await - but there is a little more work to do. Async await effectively creates synchronous blocking code, which is the kind of code you might be more used to.
As others have said, you cannot really use Javascript without a good knowledge of promises, so this is worth investing time in.
const getProducts = async () => {
const results = await fetch(`${rootUrl}api/users/getCartItems`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
},
})
const resultsJSON = await results.json()
const products = []
let counter = 0
while (counter < resultsJSON.itemsArr.length) {
const fetchedProduct = await fetch(
`${rootUrl}api/products/${resultsJSON.itemsArr[counter].item}`,
{
method: 'GET',
},
)
const fetchedProductJSON = await fetchedProduct.json()
products.push(fetchedProductJSON)
counter++
}
// Do stuff with your products array
}
getProducts()
Upvotes: 1