How to make a separate a sync function wait for another async function?

1.7k views Asked by At

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.

1

There are 1 answers

8
jfriend00 On BEST ANSWER

If you're trying to call callWeatherAPI() and pass the actual result of that to another function, then you have to await it. It is an async function and ALL async functions return a promise. The return value inside your async function becomes the resolved value of the promise. So, to get the value from the promise, you can use await or .then().

callForecastAPI(await callWeatherAPI(processSearchInput(searchInput)));

This, of course, means that this code itself will need to be inside an async function so you can use await.

For more on how an async function 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 also async and also returns a promise so to get the actual Forecast result, you will need to use await or .then() on that too.

const forecast = await callForecastAPI(await callWeatherAPI(processSearchInput(searchInput)));

Or, perhaps it's clearer with an intermediate variable:

const weather = await callWeatherAPI(processSearchInput(searchInput));
const forecast = await callForecastAPI(weather);
console.log(forecast);