1

I know that a thenable has the then method, but how does Promise know the state of the thenable objected has moved to rejected?

Example: Here, $.ajax is a thenable and can be ducktyped as a Promise if you do this:

Promise.resolve($.ajax({ url: '/test' }))

But how does the promise that this expression returns handle the catch case?

Matt
  • 978
  • 10
  • 24
  • Are there two questions ? 1) _"but how does Promise know the state of the thenable objected has moved to rejected?"_ , 2) _"how does the promise that this expression returns handle the catch case?"_ ? – guest271314 Oct 25 '15 at 16:45
  • Yes, there are. Is that okay? They are closely related. – Matt Oct 25 '15 at 18:11
  • Yes, ok from vantage , here. Only asked for clarification as to actual Question, or Questions presented – guest271314 Oct 25 '15 at 18:15

1 Answers1

4

A Promises/A+ then method does take two callbacks - one for the fulfilment and one for the rejection case. You would not use the .then(…).catch(…) pattern but .then(…, …) - the second callback is the "catch case" (notice that .catch(…) is nothing but .then(null, …)).

This is how thenables are assimilated - when the second callback gets called, they reject the promise with the error. Example:

var rejectingPromise = Promise.resolve({
    then: function(onSuccess, onError) {
        onError(new Error);
    }
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • So basically a thenable object cannot have two separate then and catch functions? – LppEdd Jun 24 '23 at 19:28
  • Ok, I tried a bit on the playground and now I understand how thenable works! – LppEdd Jun 24 '23 at 19:51
  • 1
    @LppEdd A thenable can have a `.catch` method, but it will be ignored for promise assimilation purposes - only `.then` is called. – Bergi Jun 24 '23 at 20:35