Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!