Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass an async function as a callback to an async function?

I couldn't find an answer to this anywhere...

I'm trying to use setState to update the state of my app but, I need to call an async function after setState is finished.
Can I await an async function inside the callback for setState?

 setState({foo: bar}, async () => {await doStuff()});

Also assuming that this works, can I rely on setState finishing before doStuff is called, and can I rely on doStuff being awaited?

like image 690
xyious Avatar asked Oct 17 '18 21:10

xyious


2 Answers

Yes, indeed you can. The special thing about async functions is that they always return Promises, so especially for functions whose return value is not important (callbacks, for example), you can safely put in an async function, and it would work as expected.

Taking this one step further, you can even have an async function as your componentDidMount or componentWillReceiveProps for example (but still not render, which expects a JSX element to be returned, not a Promise).

like image 195
Madara's Ghost Avatar answered Oct 20 '22 10:10

Madara's Ghost


The callback of the setState only fires when the state is updated so doStaff will not execute until state is updated. You can define the callback as async function and await inside it as any other function.

const setStateAsync = (newState) => {
   return new Promise((resolve) => {
       setState(newState, resolve);
   });

you can use it like this Ex:

 async componentDidMount() {
    await setStateAsync(newState);
    await doStuff()
 }
like image 1
Tarek Essam Avatar answered Oct 20 '22 10:10

Tarek Essam