Marlone G.
Marlone G.

Reputation: 79

Async and Promise dilemma

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';
}

Upvotes: 0

Views: 62

Answers (2)

AlpacaFur
AlpacaFur

Reputation: 192

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.

Upvotes: 0

Bergi
Bergi

Reputation: 665380

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.

Upvotes: 2

Related Questions