0

An async function already returns a Promise:

const Area = async (L, B) => L * B;
console.log(await Area(5, 4));
Area(5, 4).then(r => console.log(r));

The above can also be written using a function that returns a Promise:

const pfArea = (L, B) => new Promise(resolve => resolve(L * B));
console.log(await pfArea(5, 4));
pfArea(5, 4).then(r => console.log(r));

What does the second method offer, besides the ability to return an error condition using the reject option?

Old Geezer
  • 14,854
  • 31
  • 111
  • 198
  • 2
    `async function` returns a promise. The purpose of async/await is to simplify the syntax necessary to consume promise-based APIs. – evolutionxbox Sep 21 '22 at 09:42
  • Why are either of those functions async? Both of them resolve immediately and block the whole time – mousetail Sep 21 '22 at 09:44
  • "*besides the ability to return an error condition using the reject option?*" in the first code block, a `throw` will also reject the promise – VLAZ Sep 21 '22 at 09:44
  • Also using `throw` is equivalent to rejecting the promise – mousetail Sep 21 '22 at 09:44
  • `besides the ability to return an error condition` which you can do in an async function by returning a Promise.reject or by using `throw` ... so neither offer anything the other can't, except for simpler looking code when using async/await – Jaromanda X Sep 21 '22 at 09:47
  • Is this what you need? https://stackoverflow.com/questions/34401389/what-is-the-difference-between-javascript-promises-and-async-await – HamzaElkotb Sep 21 '22 at 09:49
  • Thanks for all the comments. Am I correct to conclude that in the evolution of promises, the second method above came first, and async/await came later to do essentially the same thing with a nicer syntax? – Old Geezer Sep 21 '22 at 09:53
  • "*Am I correct to conclude that in the evolution of promises, the second method above came first, and async/await came later*" yes. Promises were introduced in ES6. Well, even before that, as [the Promise/A+ spec](https://promisesaplus.com/) existed even earlier. Promises, as core part of JS, were added in ES6. Implementations existed as in like Bluebird or even jQuery. async/await is syntactic sugar over promises and was introduced in ES7. It was scheduled for ES6 release with promises but it failed to meet the deadline. – VLAZ Sep 21 '22 at 09:57

0 Answers0