0

If a promise is created this way:

myPromise = new Promise(function(resolve, reject) {});

Can this promise be ever resolved by any way? Obviously, the executor is not resolving it in this case, so can the promise be ever resolved?

I think if it is jQuery, it can be resolved by deferred.resolve() so that the related promise deferred.promise() is resolved.

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • 2
    If you monkeypatched `window.Promise`, yes, but pretty sure that's not what you're thinking about – CertainPerformance Jan 02 '20 at 07:49
  • @CertainPerformance you mean you actually change the mechanics of `Promise`? For example, when the promise is created, assign the `resolve` to `promise.resolve` so that the promise can resolve itself by `promise.resolve()`? – nonopolarity Jan 02 '20 at 07:54
  • Or just call `.resolve()` yourself in the constructor, if you really want to muck things up. You're not really changing the mechanics of how Promises work, you're corrupting `window.Promise` to do something non-spec-compliant – CertainPerformance Jan 02 '20 at 08:04
  • See also [Why does the Promise constructor need an executor?](https://stackoverflow.com/q/37651780/1048572) - ES6 promises don't use the deferred pattern. – Bergi Jan 02 '20 at 10:29

2 Answers2

3

No, the promise can only be resolved or rejected by the resolve and reject functions, respectively.

If these functions aren't called nor exposed, the promise will remain in pending state forever.

That's also a security level, as it helps you ensure the promise you wait for will resolve to the value you expect and when you expect; and allows you to safely return an internal promise, as it is (without any hazards or leaking secrets).

To make a promise, that relies on another promise you don't have control over, but can be resolved (or rejected) manually, regardless of the original, you can use the Promise.race() function:

//The original promise that may pend forever
const original = new Promise(()=>{})

//Controller promise, whose resolver is exposed (or contains the logic needed for "manual" resolution)
let resolve
const controller = new Promise(rs=>{resolve=rs})

//The promise you wait for (and can be resolved or rejected either by `original` or `controller`)
const mixed = Promise.race([original,controller])

mixed.then(console.log)

setTimeout(()=>resolve('Resolved'), 2000)
FZs
  • 16,581
  • 13
  • 41
  • 50
-1

Assign the resolve function to a variable outside the scope of the promise

David Bradshaw
  • 11,859
  • 3
  • 41
  • 70