Javascript 如何将async Wait与React componentDidMount()方法一起使用?

Javascript 如何将async Wait与React componentDidMount()方法一起使用?,javascript,reactjs,Javascript,Reactjs,我想用ReactcomponentDidMount()方法使用async/wait,但我发现wait是一个保留字错误。我还尝试将语句包装在立即调用的函数中,但没有帮助 async componentDidMount() { this.geoLocation.getAddress().then(location => { if (location.address != null && location.error != "undefined") { l

我想用React
componentDidMount()
方法使用
async/wait
,但我发现wait是一个保留字错误。我还尝试将语句包装在立即调用的函数中,但没有帮助

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);
    } 
  });
}
如果我删除
wait
关键字,那么我会在console.log中得到
null
,但是如果我在
fifteenMins=data[“forecast”]之前做console log然后我得到数据

相关问题:

如果您正在使用wait,则不必使用wait

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


async
函数总是返回承诺。由于
componentDidMount
不是作为
async
函数设计/记录的,因此React不会对它返回的承诺做任何事情。如果使用
async
函数执行此操作,请确保将其所有代码包装在
try
/
catch
中,以便捕获所有错误,并且不会导致未处理的异常(成为未处理的拒绝)

问题是您试图在非
异步
函数中使用
wait
:您传递的回调
then
。当使用
async
/
wait
时,您几乎从不使用
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
  }
}
或者通过使用iLife避免从
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
函数非常方便):


旁注:这两行:

const data = await this.getFifteenMinsData(y, x);
let fifteenMins = data["forecasts"];
如果愿意,可以这样编写,将结果分解为
fifteenMins
变量:

let {fifteenMins: forecasts} = await this.getFifteenMinsData(y, x);
类似地,如果您决定使用非
async
版本,您可以在
然后
处理程序的参数列表中执行此操作:

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

你的节点版本是什么?我仍然得到相同的错误。也就是说,wait是保留字。let location=wait this.geoLocation.getAddress()//如果(location.address!=null&&location.error!=“undefined”){let-fifteenMins=[];let-data=等待此操作。getFifteenMinsData(y,x);fifteenMins=data[“forecast”];console.log(fifteenMins);}回答得很好。感谢那些用谷歌搜索到这个网站的未来人们。如果我错了,请纠正我的错误,但尽管承诺确实没有被使用,但将
async
添加到
componentDidMount()
以简单地启用async wait的使用,而不使用IFEE(也就是说,它的类型更少)并没有害处。取舍是,对于新开发人员来说,第一次阅读代码可能不太清楚。
let {fifteenMins: forecasts} = await this.getFifteenMinsData(y, x);
.then(({fifteenMins: forecasts}) => {
  console.log(fifteenMins);
});