1

Please see this minimum example:

I have data like this:

const testObject = { test: 'foo' };

And my main function is this:

Cause error

// This cause error
function handleResponse(response) {
  return response.json().then(Promise.reject); // Please notice this line
}

try {
  await handleResponse({
    json: () => Promise.resolve(testObject),
  });
} catch (err) {
  console.log(err);
  // => TypeError: PromiseReject called on non-object
}

And this one works:

Correct


// This works
function handleResponse(response) {
  return response.json().then((res) => Promise.reject(res)); // Please notice this line
}

try {
  await handleResponse({
    json: () => Promise.resolve(testObject),
  });
} catch (err) {
  console.log(err);
  // => {test: "foo"}
}

Why is this happening? What did I missing?

Joseph
  • 3,974
  • 7
  • 34
  • 67

1 Answers1

3

something.then(Promise.reject) gets a reference to the reject method and passes just that function reference. It no longer has any connection to the Promise object. This means that the this value when the reject() method is called will be incorrect and it does not allow that.

As Patrick mentioned in a comment, it's the same reason you can't do this:

let reject = Promise.reject;
reject("whatever");

Methods need to be called with the context of their object unless they are specifically designed to not need the context of their object (there are some instances of that).

If you want a shortcut, you could do this:

something.then(Promise.reject.bind(Promise))

That will bind the Promise object to the method (by essentially creating a stub function that calls it as Promise.reject()).

Other related answers:

Why does this throw an undefined exception?

When you pass 'this' as an argument

Object methods assigned to variables or function arguments fail when invoked

Assiging a method to a variable in Javascript

Uncaught TypeError: this.method is not a function - Node js class export

jfriend00
  • 683,504
  • 96
  • 985
  • 979