Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
How to make async wait for result

I have a class like this (simplified):

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 )();
        });
    }    
}

For some reason the const success = await this.fetchResult(action); does not wait for the result. It immediately proceeds, resulting in and 'undefined' value.

In the background the fetch is being done. How can I make it wait for the result?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I believe the issue is that you are not resolving the response from your request, try returning a promise and resolving only when you have your response (or 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);
   }
}

Remove the async from fetchResult there is no reason for it. You're awaiting the result of the Promise in fetchResult, you only need the async keyword if fetch result is written in async await as well:

await res = fetch(url)
about 4 years ago · Juan Pablo Isaza Relatório

0

Thanks @Toto Nabendo and @ggorlen!

Working solution:

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda