【问题标题】:React class component issue in order of execution按执行顺序反应类组件问题
【发布时间】:2021-07-19 11:46:57
【问题描述】:

我的 React 类组件中有以下代码。

由于某种原因,我观察到,在 componentDidMount 内部,尽管在调用 this.getKeyForNextRequest() 之前有关键字 await,但执行会跳转到下一个调用 this.loadGrids()

我在这里做错了吗?

async componentDidMount() {
    await this.getKeyForNextRequest();
    await this.loadGrids();
}

getKeyForNextRequest = async () => {
    const dataRequester = new DataRequester({
      dataSource: `${URL}`,
      requestType: "POST",
      params: {
      },
      successCallback: response => {
        console.log(response);
      }
});

dataRequester.requestData();
}
loadGrids = async () => {
    await this.loadGrid1ColumnDefs();
    this.loadGrid1Data();
    await this.loadGrid2ColumnDefs();
    this.loadGrid2Data();
}

【问题讨论】:

  • 你没有从 getKeyForNextRequest 方法返回一个承诺
  • 您不需要在successCallback 中返回解析为response 的承诺吗? getKeyForNextRequest 返回一个承诺,但它会立即解析为 undefined,而不是与 successCallback 有任何关系...
  • getKeyForNextRequest 不返回值,因此该函数立即解析。没有什么可以等待的。
  • @DrewReese - 谢谢...我需要在 getKeyForNextRequest 中添加什么?基本上,我在 getKeyForNextRequest 的“successCallback”中设置了一个状态/键,并将用于下一个 AJAX 调用(即用于 loadGrid1Data)
  • 不知道,我猜这取决于您要等待什么。也许return dataRequester 和/或(或两者)返回一个Promise 并添加一个调用来解析successCallback 函数?更新:见@ggorlen 的回答。

标签: reactjs async-await react-class-based-component


【解决方案1】:

您可以尝试使用Promise 构造函数:

getKeyForNextRequest = () => {
  return new Promise((resolve, reject) => {
    const dataRequester = new DataRequester({
      dataSource: `${URL}`,
      requestType: "POST",
      params: {},
      successCallback: response => {
        console.log(response);
        resolve(response);
      }
    });
  });
}

这可确保您等待相关的承诺,该承诺仅在 successCallback 完成后解决,而不是像您目前拥有的那样立即解决为 undefined

这叫"promisifying" the callback

如果DataRequester 提供基于承诺的模式,请使用该模式而不是承诺回调。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多