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

198
Views
Cambiar de .then a async/await en la aplicación React (con fetch y forEach)

Escribí una función para obtener datos de la API de Hacker News con los métodos fetch y .then. Eso funcionó, pero me gustaría aprender a usar el método async/await. Por alguna razón, la última búsqueda dentro del bucle forEach devuelve undefined. ¿Algúna idea de cómo arreglar esto?

Aquí está el código original:

 componentDidMount() { // Get the top 20 post ids fetch("https://hacker-news.firebaseio.com/v0/beststories.json") .then(res => res.json()) .then(json => { let topIds = json.slice(0, 20) this.setState({ topIds: topIds }) return topIds }) // Get the posts based on the ids .then(ids => { ids.forEach(id => { fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`) .then(res => res.json()) .then(data => { let thisPost = data this.setState({ topPosts: [...this.state.topPosts, thisPost] }) }) }) }) }

Aquí está la nueva versión:

 async componentDidMount() { this.getIds() } // Get the ID's async getIds() { // Get the top 20 post ids const res = await fetch("https://hacker-news.firebaseio.com/v0/beststories.json") const json = await res.json() const topIds = await json.slice(0, 20) this.setState({ topIds: topIds }) this.getPosts() } // Get the posts async getPosts() { const posts = this.state.topIds.forEach(id => { fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`) }) const thisPost = await posts.json() // Posts returnes as undefined this.setState({ topPosts: [...this.state.topPosts, thisPost] }) }

Intenté agregar asíncronos y esperas en todo el bucle forEach, pero no funcionó. También traté de convertirlo a for of loop, pero obtuve el mismo resultado (indefinido).

¡Muchas gracias por adelantado!

Editado: resuelto esto, aquí está la versión de trabajo:

 // Get the posts async getPosts() { for (const id of this.state.topIds) { const post = await fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`) const thisPost = await post.json() this.setState({ topPosts: [...this.state.topPosts, thisPost] }) } }
about 4 years ago · Juan Pablo Isaza
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!