Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

200
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda