【问题标题】:Execute function right after previous function finishes (in fetch)在前一个函数完成后立即执行函数(在 fetch 中)
【发布时间】:2018-01-25 14:20:34
【问题描述】:

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

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

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

【问题讨论】:

  • 如果您使用的是 ES7,请尝试查看 asyncawait

标签: javascript reactjs asynchronous react-native fetch


【解决方案1】:

嗯,有什么问题:

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

handleTokenExpiration 你有:

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

【讨论】:

    猜你喜欢
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多