0

Both this functions returns a Promise. So what is the difference between this two approaches? I can't believe that it's just a personal preferences.

function somePromise(){
   return new Promise((resolve, reject) => {
      resolve(':D');
   });
}


async function someAsync(){
   return ':D';
}
Marlone G.
  • 79
  • 1
  • 4
  • 1
    Async functions are essentially a cleaner way to work with asynchronous code in JavaScript, Async/Await was created to simplify the process of working with and writing chained promises. 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. https://medium.com/front-end-hacking/callbacks-promises-and-async-await-ad4756e01d90 – Jérôme Teisseire Nov 24 '18 at 19:58
  • `async` returns an implicit promise if you don't return one, it's part of the evolving javascript syntax standard. It lets you use `await` inside the function as well. suggested reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function – Andy Ray Nov 24 '18 at 19:58
  • 1
    What's the "dilemma" that is mentioned? – Claies Nov 24 '18 at 20:00

2 Answers2

2

The second one uses a more modern language feature which might not be available in all environments. That's about it.

The new Promise constructor is still necessary to create promises when you have asynchronous functions that don't return promises already. And of course, in your specific example you created a promise that is immediately resolved with a synchronously obtained value, so you could have written return Promise.resolve(':D'); as a third option.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

The first function is a traditional function that manually returns a promise that, in turn, resolves to :D.

The second function is an asynchronous function (hence async). Asynchronous functions return promises by default so it also returns a promise.

Overall, the approaches are very similar, except that you can use await from inside async functions to avoid nesting too many callbacks. The one caveat to using async is that it isn't as widely supported as the first option.

AlpacaFur
  • 194
  • 2
  • 12