在componentDidMount中堆栈函数调用的最佳方法

时间:2018-01-31 20:43:14

标签: javascript reactjs chaining

componentDidMount = () => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.props.syncFirebaseToStore(user);
        thenCallThis()
        thenCallThis2()
      }
  }

最好的办法是做什么?基本上我想调用3个函数,但只能在前一个函数完成后执行?

我尝试使用解决新的Promise但不要认为我的语法正确。我想用.then()理想地链接它

3 个答案:

答案 0 :(得分:0)

如果您的函数已经返回Promise个实例 - 很容易将它们链接起来并附加错误处理程序,如下所示:

componentDidMount = () => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        //Make sure that this call and the rest return Promises
        this.props.syncFirebaseToStore(user)
         .then(callThis1)
         .then(callThis2)
         .catch((err) => {console.error(err)})

      }
  }

假设您想要在链中传递参数,以便前一个调用返回下一个调用的内容,那么您将执行以下操作:

  this.props.syncFirebaseToStore(user) //returns result1 when Promise resolved
             .then((results1) => {return callThis1(results1)}) //consumes results1, returns results2
             .then((results2) => {return callThis2(results2)})
             .catch((err) => {console.error(err)})

答案 1 :(得分:0)

承诺:

componentDidMount = () => {
    return firebase.auth().onAuthStateChanged((user) => {
        if (!user) return Promise.reject('No user!')

        return this.props.syncFirebaseToStore(user)
          .then(thenCallThis)
          .then(thenCallThis2)
    })
}

注意: 我假设this.props.syncFirebaseToStore()返回一个promise。 在curlies中包装箭头函数体会导致隐式返回。

答案 2 :(得分:-1)

使用异步等待上述代码可以这样编写

componentDidMount() {
    firebase.auth().onAuthStateChanged(async function(user) => {
      if (user) {
        await this.props.syncFirebaseToStore(user);
        await thenCallThis()
        await thenCallThis2()
      }
  }
}