如何通过 React componentDidMount() 方法使用异步等待?

IT技术 javascript reactjs
2022-07-08 00:44:14

我想使用async/waitReactcomponentDidMount()方法,但我得到 await 是一个保留字错误。我还尝试将语句包装在立即调用函数中,但它没有帮助。

async componentDidMount() {
  this.geoLocation.getAddress().then(location => {
    if (location.address != null && location.error != "undefined") {
      let fifteenMins = [];
      await this.getFifteenMinsData(y, x).then(
        data => {
          fifteenMins = data["forecasts"];
        }
      );
        console.log(fifteenMins);
    } 
  });
}

如果我删除await关键字,那么我会null进入 console.log,但如果我在此之前进行控制台日志,fifteenMins = data["forecasts"];那么我会得到数据。

相关问题: 等待是异步函数中的保留字错误

2个回答

async函数总是返回Promise。由于componentDidMount没有设计/记录为async函数,因此 React 不会对其返回的Promise做任何事情。async如果您为此使用函数,请确保将其所有代码包装在try/中catch,以便捕获所有错误并且您不会最终遇到未处理的异常(这将成为未处理的拒绝)。

问题是您试图await在非async函数中使用:您传递的回调then使用async/await时,您几乎从不使用then. 反而:

async componentDidMount() {
  try {
    const location = await this.geoLocation.getAddress();
    if (location.address != null && location.error != "undefined") {
      const data = await this.getFifteenMinsData(y, x);
      let fifteenMins = data["forecasts"];
      console.log(fifteenMins);
    } 
  } catch (err) {
      // Do something with the fact an error occurred
  }
}

componentDidMount或者通过使用 IIFE避免返回Promise:

componentDidMount() {
  (async () => {
    const location = await this.geoLocation.getAddress();
    if (location.address != null && location.error != "undefined") {
      const data = await this.getFifteenMinsData(y, x);
      let fifteenMins = data["forecasts"];
      console.log(fifteenMins);
    } 
  })()
  .catch(error => {
    // Do something with the fact an error occurred
  });
}

或者根本不使用async函数(但async函数真的很方便):

componentDidMount() {
  this.geoLocation.getAddress()
    .then(location => {
      if (location.address != null && location.error != "undefined") {
        return this.getFifteenMinsData(y, x)
          .then(data => {
            let fifteenMins = data["forecasts"];
            console.log(fifteenMins);
          });
      } 
    })
    .catch(error => {
      // Do something with the fact an error occurred
    });
}

旁注:这对线:

const data = await this.getFifteenMinsData(y, x);
let fifteenMins = data["forecasts"];

如果你愿意,可以这样写,将结果解构到fifteenMins变量中:

let {fifteenMins: forecasts} = await this.getFifteenMinsData(y, x);

同样,如果您确实决定使用非async版本,您可以在then处理程序的参数列表中执行此操作:

.then(({fifteenMins: forecasts}) => {
  console.log(fifteenMins);
});

如果你正在使用 await 你不必使用 then

let data=  await this.getFifteenMinsData(y, x);

编辑

let location = await this.geoLocation.getAddress();
  //do your stuff
  if (location.address != null && location.error != "undefined") {
    let fifteenMins = [];
    let data = await this.getFifteenMinsData(y, x);
    fifteenMins = data["forecasts"];
      console.log(fifteenMins);
  }