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

时间:2018-08-15 16:06:20

标签: javascript reactjs

我想将async/wait与React componentDidMount()方法一起使用,但出现 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关键字,那么我在console.log中得到了null,但是如果我在fifteenMins = data["forecasts"];之前得到了控制台日志,那么我得到了数据。

相关问题: Await is a reserved word error inside async function

2 个答案:

答案 0 :(得分:5)

async函数始终返回承诺。由于componentDidMount并未作为async函数进行设计/记录,因此React对其返回的承诺不做任何事情。如果为此使用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
  }
}

或者避免通过使用IIFE从componentDidMount返回承诺:

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);
});

答案 1 :(得分:1)

如果您正在使用等待,则不必使用

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);
  }