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

129
Visualizações
Javascript shortand for using await in a callback

It makes sense that you cannot use await inside of an synchronous function. Consider the following snippet

fetch('.../userdata.json')
.then(async res => {
    const data = await res.json();
    setData(state => state.data = data)
    // setData requires a sync callback in order to work
});

I have to define data so that I'm not using await in the callback, which feels a little redundant. Is there shorthand that would allow me to await in the callback?

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

0

Either use async/await or use callbacks. I don't know what "shorthand" you're looking for, but you can use await overall if the enclosing function is async. For example:

const someFunc = async () => {
  const res = await fetch('.../userdata.json');
  const data = await res.json();
  setData(state => state.data = data);
};
someFunc();

Alternatively, if you're not in an async function, you can't use await. So this operation would involve callbacks passed to .then() on Promises:

fetch('.../userdata.json')
  .then(res => res.json())
  .then(data => {
    setData(state => state.data = data);
  });
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