【问题标题】:Using Async await in react component在反应组件中使用异步等待
【发布时间】:2019-07-23 00:14:19
【问题描述】:

因此,我创建了一个组件,该组件使用我提供的道具发送发布请求。

虽然我熟悉 Async await,但由于某种原因,我似乎无法让它返回已履行承诺的实际值,而只是等待处理。

我已尝试使用更多功能进行包装,因为我知道承诺没有得到解决。

我觉得我错过了什么。

下面是我的代码示例

export default class PostController extends React.Component {
constructor(props) {
    super(props)
}
Wrapper = (body) => {
    try{
        let x = this.Send(body);
        return x;
        console.log(x)
    }catch(e){console.log(e)}
}
Send = async (body) => {
        try{
            let data = await this.Post(body);
            return data;
        }catch(e){console.warn(e)}       
}
Post = async (body) => {
    try{
        const options = {
            method: 'POST',
            uri: 'XXXXXXXXXXXXXXXXXXXX',
            body: body
        }
        const data = await rp(options);
        return data; 
    }catch(e){console.warn(e)}
}
render(props) {
    let jsonBody = JSON.stringify(this.props.data)
    const returnData = this.Wrapper(jsonBody)
    console.log(returnData)

        return(
            <div>
                 {(!this.props.data.pw) ? 'Retrieved Password: ' + returnData.message : 'Generated PassWord!:' + returnData.message }
            </div>
        )
    }

}

【问题讨论】:

  • 你能告诉我rp(options) 是什么,为什么它在等待什么吗?...
  • 请求承诺,它是一个将常规请求库包装在承诺中的库。

标签: javascript reactjs promise request-promise


【解决方案1】:

我认为您需要更多关于 JS 中的 async/await 的信息。

async function 总是返回一个承诺。 所以Wrapper 中的x 是一个承诺。因为你不使用await/async。

应该是这样的。

async Wrapper = (body) => {
    try{
        let x = await this.Send(body); // <-- missing await here
        return x;
    }catch(e){console.log(e)}
}

但是,render 中的代码不起作用。因为this.Wrapper() 现在返回一个承诺。 ->returnData is a promise。并且render 方法不能是异步函数:)

render(props) {
    //... 
    const returnData = this.Wrapper(jsonBody) // <-- returnData here is a promise.
    //...

为了让事情顺利进行。

你必须使用state。在componentDidMount 或componentDidUpdate 中拨打this.Wrapper。例如:

constructor() {
    // ...
    this.state = { returnData: null }
}
async componentDidMount() {
   const returnData = await this.Post(...); // Using await to get the result of async func
   this.setState({ returnData });
}

async Post(body) {
  try{
    const options = {
      method: 'POST',
      uri: 'XXXXXXXXXXXXXXXXXXXX',
      body: body
    }
    return rp(options); // define await then return is unnecessary 
  }catch(e){console.warn(e)}
}

render() {
     const { returnData } = this.state;
    // ... Do the rest

}

【讨论】:

  • 太棒了!没有意识到可以像这样使用componentdidmount!我有很多东西要学!
  • @Scottt:如果答案是您所需要的。把它标记为正确答案!
  • 但这不会不必要地为每个装载获取帖子吗?这将导致代码效率非常低。
  • 意外的保留字“等待”。我在异步 componentDidMount() 中使用它很奇怪!
  • @Suisse 也许您使用的是不支持异步等待的旧版本?
【解决方案2】:

我相信您应该尝试将 Wrapper 函数标记为异步并在控制台记录 returnData 之前等待它。同样在 Wrapper 内的 Send() 上等待。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 2022-01-15
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    相关资源
    最近更新 更多