Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should the Promise constructor be used explicitly? How to use it appropriately?

According to MDN documentation for Promise,

The Promise() constructor creates Promise objects. It is primarily used to wrap callback-based APIs that do not already support promises.

With that in mind:

  1. Am I right to assume that at a low level, the functions that already support promises would be doing this right, i.e constructing a promise using Promise and returning it?
  2. Is there a better way to create a promise other than using the Promise constructor function?
  3. If you do end up using the Promise constructor, you have to register a callback somewhere right? I mean you can't avoid having a callback that at-least resolves the promise? In other words, we have to wrap it like this somewhere in the library, correct?
like image 872
Nishant Avatar asked Nov 29 '25 16:11

Nishant


1 Answers

  1. At the lowest level? Yes, probably.
  2. Depends on the context. If the value you want to resolve the value to is already available, then you'd use Promise.resolve(theValue). If you want to wait for multiple promises you'd use Promise.all(allThePromises). And of course every call to .then returns a new promise.
  3. If you want to do anything with the value of a promise, then yes, you have to pass a callback to .then. There is no other way to get the value.

Having said all that, ES2017 introduced async functions which are basically syntactic sugar for promises. async functions always return a promise and you can use await to unwrap promises. Example:

async function get() {
  return await Promise.resolve(42);
}

get().then(console.log);
like image 112
Felix Kling Avatar answered Dec 02 '25 04:12

Felix Kling