async 函数总是返回承诺。由于componentDidMount 没有被设计/记录为async 函数,因此React 不会对它返回的承诺做任何事情。如果您为此使用async 函数,请确保将其所有代码包装在try/catch 中,以便捕获所有错误并且您不会以未处理的异常结束(这将成为未处理的拒绝) .
问题是您试图在非async 函数中使用await:您传递的回调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);
});