我想将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"];
之前得到了控制台日志,那么我得到了数据。
答案 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);
}