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