How to treat `Promise.reject` as a first class function?

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

      

+3


source to share


2 answers


spec defines Promise.reject

as follows (emphasis mine):

25.4.4.4 Promise.reject( r )

The reject function returns a new promise rejected by the passed argument.

  • Let C be the value.
  • If type (C) is not an object, throw an exception TypeError

    .
  • May the promise be possible? NewPromiseCapability (C).
  • Execute? Challenge (promise. Opportunity [[Reject]], undefined, "r").
  • Return of the promise. [[Promise]].

NOTE. The function reject

expects this value is a constructor function that supports the constructor convention parameter Promise

.

As you can tell from this, it Promise.reject

expects to be called in the Promise constructor (either native promises or some other compatible implementation). When viewed Promise.reject

as a function of a first class like this, you call it on a global object that is not a Promise constructor and therefore fails. 1

If you need to use Promise.reject

this way, I would recommend linking it first:



var f = Promise.reject.bind(Promise);
f(3); // Promise {[[PromiseStatus]]: "rejected", [[PromiseValue]]: 3}

      


1 I'm not entirely sure why the global object is not considered an object as it Promise.reject.call({ })

gives Uncaught TypeError: object is not a constructor

.

+5


source


I believe this is because it reject

is defined as a static function of the Promise object.

Thus, you cannot call it like you did above, since it is called directly on the class and not on an instance of the class.

More on static functions and when they can and cannot be called here:



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

You can wrap it in a function:

function promiseReject(x) {
   return Promise.reject(x);
}

var f = promiseReject;

var out = f(3);

      

0


source







All Articles