async
functions always return promises. Since componentDidMount
isn't designed/documented as an async
function, React doesn't do anything with the promise it returns. If you use an async
function for this, be sure to wrap all its code in try
/catch
so that all errors are caught and you don't end up with an unhandled exception (which becomes an unhandled rejection).
The problem is that you're trying to use await
in a non-async
function: The callback you've passed then
. When using async
/await
, you almost never use then
. Instead:
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
}
}
Or avoiding returning a promise from componentDidMount
by using an IIFE:
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
});
}
Or don't use an async
function at all (but async
functions are really handy):
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
});
}
Side note: This pair of lines:
const data = await this.getFifteenMinsData(y, x);
let fifteenMins = data["forecasts"];
can be written like this if you like, destructuring the result into the fifteenMins
variable:
let {fifteenMins: forecasts} = await this.getFifteenMinsData(y, x);
Similarly, if you did decide to go with the non-async
version, you can do that in the parameter list of the then
handler:
.then(({fifteenMins: forecasts}) => {
console.log(fifteenMins);
});