Async functions always return a promise - Lets deep into the Async world

Async functions are a way to make the asynchrounous operation synchronously by awaiting for the resopnse. Lets see it in the example straight away,

// Normal async function - Returning promise
const getCats = async () => {
  return new Promise((resolve, reject) =>
    setTimeout(
      () =>
        resolve([
          {
            name: 'tiger',
          },
          {
            name: 'jimmy',
          },
        ]),
      2000,
    ),
  )
}

// Self invoking async function
;(async () => {
  console.log(getCats()) // Promise { <pending> }
  const cats = await getCats()
  console.log(cats) // [ { name: 'tiger' }, { name: 'jimmy' } ]
})()

As you can see, we are returning a promise in our example.

Now lets see the next example by returning direct JSON array,

// async function - Returning JSON
const getCatsJson = async () => {
  return [
    {
      name: 'tiger',
    },
    {
      name: 'jimmy',
    },
  ]
}

// Self invoking async function
;(async () => {
  console.log(getCatsJson()) // Promise { [ { name: 'tiger' }, { name: 'jimmy' } ] }
  const catsJson = await getCatsJson()
  console.log(catsJson) // [ { name: 'tiger' }, { name: 'jimmy' } ]
})()

As you can check the console log, even though we returned a JSON object from the async function. It was wrapped as a promise. So we still need to await and resolve the promise.

You can always resolve the async without await using promise way,

getCatsJson().then(console.log) // [ { name: 'tiger' }, { name: 'jimmy' } ]

You can check the examples here,

https://codesandbox.io/s/async-promise-return-value-fpis9

Hope, this helps you to understand how async returns the value by wrapping it as a Promise šŸ˜‹

šŸ”„ Limited Time Offer
Coding with AI: Learn to build a SaaS MVP in 10 days

Coding with AI: Learn to build a SaaS MVP in 10 days

Master practical AI development to build and launch your startup MVP in weeks instead of months. Learn to leverage AI tools and APIs effectively.

  • šŸŽÆ Build real MVP: AI-powered SaaS from idea to launch
  • šŸ¤– Integrate ChatGPT, Claude, and other AI APIs efficiently
  • šŸ’° Implement AI features users will pay for
  • āš”ļø AI-assisted coding patterns to ship 10x faster
  • šŸš€ Launch your product in 10 days, not 10 months