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

105
Visualizações
how to get result data from async fetch inside another function

I'm trying to use async fetch call to get data from the server but the result looks like an empty async function. what am I doing wrong?

this is my code

  function initAutoComplete (selector, params = []) {
    let config = {
      selector: selector, 
      data: {
        src: async () => {
          try {
            let myurl = `/component/get_states?country_id=64`; // http://localhost
            const response = await fetch(myurl)
            const source = await response.json();
            console.log('source', source); // ==> this doesn't even appear in the console log
            return source;
          } catch (err) {
            return err;
          }
        },
        keys: ["state_name"],
        cache: true,
      },
    };
    console.log('config', config.data);
    return config;
  }
  const asd = initAutoComplete('#state_name');
  console.log('asd', asd.data);

this is the result in the developer tools result from developer tools

although when I used postman to test the url, it shows the data as expected

[
    {
        "id": "17",
        "state_name": "Bali",
        "country_name": "Indonesia"
    },
    {
        "id": "16",
        "state_name": "Banten",
        "country_name": "Indonesia"
    },
    {
        "id": "7",
        "state_name": "Bengkulu",
        "country_name": "Indonesia"
    },
]
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Your code shows calling initAutoComplete(), but all that does is define a config object that contains a data.src() function, but nothing you show ever calls that function.

So, per this code that function is never executed and never should be. The function has been defined, but not called.

You would use this:

const asd = initAutoComplete('#state_name');
asd.data.src().then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

to actually call that async function.


In addition, return err is probably the wrong way to do error handling in your src() function. You WANT the promise that the async function returns to reject when you get an error. As you're doing it now, it's quite a pain for the caller to tell the difference between a result and an error condition since you're just returning a value both ways. The caller would probably have to check the resolved value to see if it was an instanceof Error to discern if the result was an error or not.

If you remove the try/catch in your src() function, then the reject will happen automatically which is likely what you want.

about 4 years ago · Santiago Trujillo 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