简体   繁体   English

在React中的Promise中调用Async函数

[英]Calling Async functions inside promise in React

I am developing an application in React. 我正在React中开发一个应用程序。 It has a simple search box, on submit , i am calling api1, which returns an array of data. 它有一个简单的搜索框,在Submit上,我正在调用api1,它返回数据数组。 For each of the item in the array, i need to call api2 - which should be async. 对于数组中的每个项目,我需要调用api2-应该是异步的。 Currently the code is something like this: 当前的代码是这样的:

onSubmit() { 
    api1(textboxvalue).then(data => { 
        let currentComponent = this      
        if(data matches condition1) {
        currentComponent.state.arrayOfElements1.push(data);
        }               

        if(data matches condition2) {
        currentComponent.state.arrayOfElements2.push(data);
        }               

        const arrayOfElements1 = this.state.arrayOfElements1
        arrayOfElements1.map(function (element) {
        api2(element) -> set this.state.data1loaded

        })

        const arrayOfElements2 = this.state.arrayOfElements2
        arrayOfElements2.map(function (element) {
        api2(element) -> set this.state.data2loaded

    })

}

Requirement is check data1loaded and data2loaded states in render asynchronously. 要求检查异步渲染中的data1loaded和data2loaded状态。 But with the above code, render is called only after promise of api1 completes 但是使用以上代码,仅在api1的承诺完成后才调用render

Any thoughts ? 有什么想法吗 ?

You're pushing the result to the state, instead of using setState method that would re-render component with the new state. 您将结果推送到状态,而不是使用setState方法来重新渲染具有新状态的组件。 This has nothing to do with the async nature of Promises, but rather the way React works (simplified: updating state and passing state and props to components which causes them to render). 这与Promises的异步性质无关,而是与React的工作方式有关(简化:更新状态并将状态和prop传递给导致它们呈现的组件)。

I suggest brushing up on React basics before moving forward. 我建议在继续之前重新学习React基础知识

@amirKovacevic is totally correct. @amirKovacevic是完全正确的。 You should NEVER mutate state directly: https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly 您永远不要直接更改状态: https//reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-direct

I don't perfectly understand your code, but I imagine you want to do something like this: 我不太了解您的代码,但我想您想执行以下操作:

onSubmit() {
  api1(textboxvalue).then(data => {
    if(/* data matches condition1 */) {
      this.setState(prevState => ({
        arrayOfElements1: [...prevState.arrayOfElements1, data]
      }), () => {
        const requests1 = Promise.all(this.state.arrayOfElements1.map(function 
          (element) {
            return api2(element)
          })).then(data => this.setState({ data1loaded: true })) // I assume you want to have an indication loading was complete
      })
    }
  })
}

Notice the callback hell I climbed myself into because I didn't use async/await. 注意,由于我没有使用async / await,因此我陷入了回调地狱。 Also notice I used setState callback: https://reactjs.org/docs/react-component.html#setstate 还要注意,我使用了setState回调: https : //reactjs.org/docs/react-component.html#setstate

Setting the state is asynchronous, so you shouldn't use it directly after using setState , at least not if you want to have the new values. 设置状态是异步的,因此,在使用setState ,不应直接使用它,至少如果要使用新值,则不setState

Also, my example is only for the first array of elements. 另外,我的示例仅适用于第一个元素数组。

Oh, and I'm new on SO, so sorry if anything is not up to usual SO comment standards. 哦,我是SO的新手,如果有任何不符合常规SO评论标准的情况,那么抱歉。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM