question is: if a function runs async but does not return a promise itself (returns void), then will "awaiting" it still work. I thought that 'await' only works if the function returns a promise and not void.
So, in my async function in react I am doing something like this
class Form extends Component {
submitForm = async event => {
event.preventDefault();
const isFormValid = await this.validateForm();
if(!isFormValid) {
return;
}
//some logic
}
validateForm = async () => {
let isValid = false;
//some logic
await this.setState(prevState => {});
//some more logic
return isValid; //this is set inside the setState
}
}
Here I am awaiting this.setState()
, but this.setState()
does not return a promise, although it is a function that runs asynchronously. At first I thought this would not work. But after debugging and trying it out for a few times, it seems to work. The isValid
value is returned only when the this.setState
completes its execution (thus successfully setting the isValid
value internally depending upon the state).
Although my code is working, it has left me kind of confused, as though why this is working. I read somewhere that await waits till the value on the right side is resolved. But I thought that was only applicable if the expression on the right side was a Promise
.
I thought a more valid or correct way was as described in this article I found https://medium.com/front-end-weekly/async-await-with-react-lifecycle-methods-802e7760d802 which makes sense since the custom setStateAsync
function returns a promise.
For those of you who can't access the article here is the relevant snippet
class AwesomeProject extends Component {
state = {}
setStateAsync(state) {
return new Promise((resolve) => {
this.setState(state, resolve)
});
}
async componentDidMount() {
StatusBar.setNetworkActivityIndicatorVisible(true)
const res = await fetch('https://api.ipify.org?format=json')
const {ip} = await res.json()
await this.setStateAsync({ipAddress: ip})
StatusBar.setNetworkActivityIndicatorVisible(false)
}
}
edit: (title changed from "Using await for functions NOT returing a promise")
edit2: I read async/await implicitly returns promise? question before I posted my question. I do get that assigning a function the async keyword turns it into something that returns a promise. But I didn't know that just using the await keyword also had the same effect. As this is not mentioned anywhere that I looked. As I said, if setState was some function that I had defined, I get that I could turn it into a promise returning function by assigning the async keyword to it. But I didn't know I could do the same by not assigning the async but just using await while calling it.