Wrapping promise in async/await

10,378

I am missing a point here as this returns a promise. Shouldn't console.log(c()) print "hello"?

No, async functions always return promises. They're not magically running asynchronous code synchronously - rather the reverse, they turn synchronous-looking code (albeit speckled with await keywords) into asynchronously running one.

You can get the result value inside the asynchronous function:

async function c() {
  const result = await test()
  console.log(result);
  return 'World';
}
c().then(console.log);

I am unclear as to whether a callback needs to be converted to a promise before wrapping it in async/await?

Yes, you can await only promises. See How do I convert an existing callback API to promises? for how to do the conversion.

Share:
10,378
cyberwombat
Author by

cyberwombat

My name is Yashua (@cyberwombat) and I am a full stack JS developer with a penchant for pixel perfect design and cutting edge tech. I am the cofounder and lead tech of LotusEngine, an automation and state machine platform. I thrive on co-creating and exploring potential ideas and helping people implement them whether through consultation or direct involvement. I am primarily based in Northern Arizona but travel often. I can equally assist you through online communication or meet you in person should our locations coincide.

Updated on July 31, 2022

Comments

  • cyberwombat
    cyberwombat almost 2 years

    I'm struggling a bit with async/await and returning a value from a Promise.

    function test () {
      return new Promise((resolve, reject) => {
        resolve('Hello')
      })
    } 
    
    async function c() {
      await test()
    }
    

    As I understood things I should be able to get a value by doing:

    console.log(c())
    

    But clearly I am missing a point here as this returns a promise. Shouldn't it print "hello"? On a similar note I am unclear as to whether a callback needs to be converted to a promise before wrapping it in async/await?