Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping promise in async/await

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?

like image 636
cyberwombat Avatar asked Aug 08 '16 21:08

cyberwombat


People also ask

Can we use promise with async await?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Does async await always return promise?

Async functions The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically. So, async ensures that the function returns a promise, and wraps non-promises in it.

How do you resolve await promise?

await is a new operator used to wait for a promise to resolve or reject. It can only be used inside an async function. Promise. all returns an array with the resolved values once all the passed-in promises have resolved.


Video Answer


2 Answers

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.

like image 187
Bergi Avatar answered Oct 17 '22 08:10

Bergi


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.

like image 42
zloctb Avatar answered Oct 17 '22 08:10

zloctb