DEV Community

Umakanthan D
Umakanthan D

Posted on

JavaScript promises and async functions

When learning async/await, I am sure you wrote that function that returns a Promise and you used async/await to check out how it works. But the reverse is also true. You can write an async function and use it as a promise. This is because, an async function anyway returns a promise.

For example,
async function myfunc() { return 'Hi';}

You can then use it like this
myfunc().then(() => console.log('got it'))

Similarly you can just replace new Promise and then calling resolve and reject, with an async function that either returns a value or throws an error and use it just like a Promise, for the simple reason, IT IS A PROMISE. Irrespective of whether you return anything or not, an async function ALWAYS RETURNS A PROMISE.

The following code should demonstrate just that. Of course, once you have an environment where async/await are supported, there is little point in using the old promise syntax.

async function f1(num) {
  if (num < 5) return 'Hello world'
  throw 'Error'
}
f1(3)
 .then((data) => console.log('Got=', data))
 .catch((e) => console.log('Error=', e))

f1(6)
 .then((data) => console.log('Got=', data))
 .catch((e) => console.log('Error=', e))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)