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

120
Visualizações
Proper way of dealing with returning from a fetch

I'm a bit new to coding in a JS/TS way and I just wanted to know the best practice when it comes to returning and handling void and values that come from a fetch. In short, I'd like to use fetch to retrieve a JSON file somewhere, extract some relevant info, and return a dict.

async function doSomething() {
    const response =  fetch(...)
    .then(response =>
        response.json().then(data => ({
            data: data,
            response: response.ok
        }))
    )
    .then(data => {
        if (!data.response) {
            console.warn("Response was not ok...")
            return null
        } else if (data.data["results"] == 0) {
            console.info("Returned no results")
            return null
        } else {
            const returned = {
                name: data.data["stuff"],
                thing: data.data["other"]
            }
            return returned
        }
    })
    .catch(error => console.error(`${error}`))

return response

TS returns an error saying that Property 'name' does not exist on type 'void | {...} when I want to use the values of the dict. The error, I completely understand. When using the function I try to do type checking to handle when it returns void, but it still raises an error for something like this:

const request = await getQuery("movie", query)
    if (request === undefined || request === null) return "I wasn't able to find your query."
    const data = {
        name: request.name
    }
}

I'm just wondering what's the best way to write and handle void, and using the dict values.

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

0

I wouldn't have the function do too much. Have it concentrate on returning some data, and let the function that calls it deal with how that data is going to be used.

If you're going to use async/await you should be consistent. Mixing async with then doesn't make a lot of sense. This way you're either going to return some data, or throw an error.

async function getData(endpoint) {
  try {
    const response = await fetch(endpoint);
    if (response.ok) {
      const { data } = await response.json();
      return data;
    } else {
      throw new Error('Response error.');
      return undefined;
    }
  } catch (err) {
    console.warn(err);
  }
}

async function main() {
  const endpoint = 'http://example.com';
  const data = await getData(endpoint);
  if (data && data.results) {
    console.log(data.results.name);
  } else {
    console.warn('No results');
  }
}

main();

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