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



Solution 1:[1]

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);
  });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1