Ad
Execute Function Right After Previous Function Finishes (in Fetch)
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.
Ad
Answer
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();
}
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad