Reputation: 1387
How is it possible to call function right after second one is finished. I have this code:
import { handleTokenExpiration } from '../../utils/tokenExpiration'
handleClick(){
fetch(someURL, {
method: "PUT",
headers: {
Authorization: `Bearer${token}`,
},
body: JSON.stringify({
note: this.state.text,
})
})
.then((response) => response.json())
.then((responseData) => {
if (responseData.success) {
Alert.alert(
'Thanks!',
[
{text: 'OK'}
],
{ cancelable: false }
)
}
else{
if(responseData.mvMessages[0].message === "your token is expired"){
handleTokenExpiration(this.props.token)
this.handleClick()
}
else{
switch (responseData.mvMessages[0].key) {
case 'note':
this.setState({
userNoteError: responseData.mvMessages[0].message,
})
break;
case 'note2':
this.setState({
userInputError: responseData.mvMessages[0].message,
})
break;
default:
this.setState({
userLastError: responseData.mvMessages[0].message,
})
}
}
}
})
.catch(error => {
console.log(error)
})
}
Basically when token expires those two function should be called. handleTokenExpiration(this.props)
and this.handleClick()
First function handles the token expiration and second one called the same function(with valid token). This works but the thing is that both functions are called couple times because of asynchronous behavior.
How is it possible to wait for handleTokenExpiration(this.props)
finish and then run this.handleClick()
?
Something similar to when we have want to run a function right after setState is finished:
this.setState({
FirstName: this.props.firstName
}, () => this.calledRightAfterSetStateisFinished())
But in this case one function after another.
Upvotes: 0
Views: 1942
Reputation: 13529
Well, what's wrong with:
handleTokenExpiration(this.props.token, () => {
this.handleClick();
});
and in handleTokenExpiration
you have:
export default function handleTokenExpiration(token, callback) {
// ... do whatever you need to do
callback();
}
Upvotes: 2