Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
Cannot call a variable inside that is defined inside .then

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) 
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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) 
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!