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

113
Vistas
Cómo hacer que async espere el resultado

Tengo una clase como esta (simplificado):

 export class Foo { constructor(el, menuItems ) { this.id = this.el.dataset.id; this.menuItems = menuItems; this.fetchResult = async function (uri) { fetch(uri, { method: 'get' }) .then(response => response.json()) .then(data => { return data.saved === true; }) .catch(function (err) { console.log('Failed ', err); return false; }); } } doAction(action) { const uri = 'foo/'+ action +'?id=' + this.id; const map = { 'close': async () => { const success = await this.fetchResult(action); console.log(success); // says undefined? } /* some other actions */ } return map[action]; } attachDialogs() { this.menuItems.addEventListener('click', (element) => { this.doAction( element.dataset.action )(); }); } }

Por alguna razón const success = await this.fetchResult(action); no espera el resultado. Continúa inmediatamente, dando como resultado un valor 'indefinido'.

En segundo plano, se está realizando la búsqueda. ¿Cómo puedo hacer que espere el resultado?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Creo que el problema es que no está resolviendo la respuesta de su solicitud, intente devolver una promesa y resolver solo cuando tenga su respuesta (o error)

 this.fetchResult = function(uri) { return new Promise((resolve, reject) => { fetch(uri, { method: 'get' }) .then(response => response.ok ? response.json() : reject(new Error(response.statusText))) .then(result => resolve(result)) } } const map = { 'close': async () => { const success = await this.fetchResult(action); } }

Elimine el asíncrono de fetchResult, no hay motivo para ello. Está esperando el resultado de Promise en fetchResult, solo necesita la palabra clave async si fetch result también está escrito en async await:

 await res = fetch(url)
about 4 years ago · Juan Pablo Isaza Denunciar

0

¡Gracias @Toto Nabendo y @ggorlen!

Solución de trabajo:

 export class Foo { constructor(el, menuItems ) { this.id = this.el.dataset.id; this.menuItems = menuItems; this.fetchResult = async function (uri) { return fetch(uri, { method: 'get' }) .then(response => response.json()) .then(data => { return data.saved === true; }) .catch(function (err) { console.log('Failed ', err); return false; }); } } async doAction(action) { const uri = 'foo/'+ action +'?id=' + this.id; const map = { 'close': async () => { const success = await this.fetchResult(action); console.log(success); } /* some other actions */ } return map[action]; } attachDialogs() { this.menuItems.addEventListener('click', (element) => { this.doAction( element.dataset.action )(); }); } }
about 4 years ago · Juan Pablo Isaza Denunciar
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