Why can I do this:
> Promise.reject(3);
< Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: 3}
But not this:
> var f = Promise.reject;
< undefined
> f(3)
< VM2366:1 Uncaught TypeError: PromiseReject called on non-object
at reject (<anonymous>)
at <anonymous>:1:1
The spec defines Promise.reject as follows (emphasis mine):
25.4.4.4
Promise.reject( r )The reject function returns a new promise rejected with the passed argument.
- Let C be the this value.
- If Type(C) is not Object, throw a
TypeErrorexception.- Let promiseCapability be ? NewPromiseCapability(C).
- Perform ? Call(promiseCapability.[[Reject]], undefined, « r »).
- Return promiseCapability.[[Promise]].
NOTE: The
rejectfunction expects its this value to be a constructor function that supports the parameter conventions of thePromiseconstructor.
As you can tell from this, Promise.reject expects to be called on a Promise constructor (either native promises or other compatible implementation). When treating Promise.reject as a first-class function like that, you're calling it on the global object, which is not a Promise constructor and therefore fails.1
If you need to use Promise.reject in this way, I'd recommend to bind it first:
var f = Promise.reject.bind(Promise);
f(3); // Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: 3}
1 I'm not exactly sure why the global object is not considered an object, though, since Promise.reject.call({ }) gives Uncaught TypeError: object is not a constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With