Javascript 如何将async Wait与React componentDidMount()方法一起使用?
我想用ReactJavascript 如何将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
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);
});