I am trying to do something with the posts(an array) that I am fetching from the database but as you can see I cannot call a variable that is defined inside .then. What is the right way to do this? All I want to do is fetch the array posts and do something with it.
function AllPosts() {
fetch('/posts/all')
.then(response => response.json())
.then(posts => {
///posts printed in console here
console.log(posts)
})
///posts not printed in console here (posts are not defined error)
console.log(posts)
}
Turn AllPosts in an async function, and await the result of the response.
async function AllPosts() {
const response = await fetch('/posts/all');
const posts = await response.json();
console.log(posts)
}