在上一个函数完成后执行函数(在获取中)

时间:2018-01-25 14:20:34

标签: javascript reactjs asynchronous react-native fetch

如何在第二个完成后立即调用函数。我有这段代码:

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

基本上当令牌过期时,应该调用这两个函数。 handleTokenExpiration(this.props)this.handleClick()

第一个函数处理令牌到期,第二个函数调用相同的函数(带有效令牌)。这可行,但事实是由于异步行为,两个函数都被称为几次。

如何等待handleTokenExpiration(this.props)完成然后再运行this.handleClick()

类似于我们想要在setState完成后立即运行函数的东西:

this.setState({
  FirstName: this.props.firstName
}, () => this.calledRightAfterSetStateisFinished())

但在这种情况下,一个接一个的功能。

1 个答案:

答案 0 :(得分:2)

嗯,出了什么问题:

handleTokenExpiration(this.props.token, () => {
  this.handleClick();
});

并且handleTokenExpiration你有:

export default function handleTokenExpiration(token, callback) {
 // ... do whatever you need to do
 callback();
}