I am unable to callback async function inside of another async function. I am receiving this in the console:
PromiseĀ {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
script.js:127 TypeError: Cannot read property 'aWeatherObjProperty' of undefined
at callForecastAPI (script.js:121)
at HTMLInputElement.<anonymous> (script.js:138)
Here is my JavaScript code:
function processSearchInput(searchInput) {
// does some math. No waiting required.
return processedSearchInput;
}
// processedSearchInput is an object
// Take processedSearchInput and call OpenWeather API
async function callWeatherAPI(processedSearchInput) {
const response = await fetch(`calling API`, { mode: 'cors' });
const weather = await response.json();
return weather;
}
// weather is an object
// Call OpenWeather Forecast API and return weatherForecast object
async function callForecastAPI(weatherObj) {
const response = await fetch(`calling API`);
const weatherForecast = await response.json();
return weatherForecast;
}
callForecastAPI(callWeatherAPI(processSearchInput(searchInput)));
I am certain weather object is being returned by callWeatherAPI as I can console.log it right before the return and can return it right before the fetch in callForecasrAPI. Thank you in advance for any advice.
If you're trying to call
callWeatherAPI()and pass the actual result of that to another function, then you have toawaitit. It is anasyncfunction and ALLasyncfunctions return a promise. The return value inside yourasyncfunction becomes the resolved value of the promise. So, to get the value from the promise, you can useawaitor.then().This, of course, means that this code itself will need to be inside an
asyncfunction so you can useawait.For more on how an
asyncfunction always return a promise see Why do I need to await an async function when it is not supposedly returning a Promise?.And,
callForecastAPI()is alsoasyncand also returns a promise so to get the actual Forecast result, you will need to useawaitor.then()on that too.Or, perhaps it's clearer with an intermediate variable: