Wrapping promise in async/await
Asked Answered
S

2

8

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?

Sunward answered 8/8, 2016 at 21:57 Comment(1)
well, no, async/await doesn't magically make asynchronous code run synchronously. Code outside of the async function still has to wait for the async function to complete.Grimbly
F
19

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.

Facesaving answered 8/8, 2016 at 22:20 Comment(0)
B
1

Async functions return a Promise. If the function throws an error, the Promise will be rejected. If the function returns a value, the Promise will be resolved.

Bobsled answered 14/2, 2018 at 13:49 Comment(1)
you should specify the sourceFlatten

© 2022 - 2024 — McMap. All rights reserved.