Why does it return a promise and not a value?

const getData = async () => {
  try {
    let userInput = form.elements.query.value
    const config = {
      params: { q: userInput }
    }

    const info = await axios.get('http://api.weatherapi.com/v1/current.json?key=eaad8b54e7f642fdac190640211410', config)

    return info.data
  }
  catch{
    console.log(e)
  }
}

When I return info.data, it just gives back a promise. Any thoughts on how this can happen?

Async functions always return a promise. JS will automatically wrap any value you return from an async function in a promise.

MDN doc on async functions

2 Likes

I think we need more information here, especially about the calling function. I ran your code against a local API endpoint and called it from an async functions with an await and got the data and not the promise.

If you don’t await the call to this function you should get a promise returned, because the await in getData is splitting the execution so that getData waits to resolve the promise while the caller, if not awaiting, continues with an unresolved promise as the (temporary) return from getData. Or in other words:

const getData = async () => {
  try {
    let userInput = form.elements.query.value
    const config = {
      params: { q: userInput }
    }

    const info = await axios.get('http://api.weatherapi.com/v1/current.json?key=eaad8b54e7f642fdac190640211410', config)

    console.log('in getData');
    console.log(info.data);

    return info.data
  }
  catch{
    console.log(e)
  }
}

// Returns promise.
console.log(getData());

returns something like

Promise { <pending> }
in getData
{
  ...data...
}

but

const getData = async () => {
  try {
    let userInput = form.elements.query.value
    const config = {
      params: { q: userInput }
    }

    const info = await axios.get('http://api.weatherapi.com/v1/current.json?key=eaad8b54e7f642fdac190640211410', config)

    console.log('in getData');
    console.log(info.data);

    return info.data
  }
  catch{
    console.log(e)
  }
}

// Returns data.
(async () => {
  const data = await getData();
  console.log(data);
})();

returns

in getData
{
  ...data...
}
{
  ...data...
}

Also note how the order of the printed data is in opposite order. And there’s the bonus use of the IIFE to boot.

1 Like