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

130
Vistas
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 Respuestas
Responde la pregunta

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 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