A. instanceof
Technically, the Javascript expression a instanceof b
checks
a
is an object (which includes functions because they are objects),
- 'b' is a constructor function - which includes classes because declarations and expressions using the
class
keyword create constructor functions,
- the value of
b.prototype
is in the inheritance chain of a
. This means either a
was constructed by b
, or otherwise somewhere in the inheritance chain of a
there is an object constructed by b
.
Given an objects inheritance chain is set to the prototype
property of its constructor, aPromise
in your code is an instance of Promise
because Promise.prototype
is the first entry in its prototype chain. The second entry in its prototype chain is Object.prototype
so aPromise
is an instance of Object
as well.
a
is constructed and initialized by Object
in response to the {..}
object initializer syntax. Object.prototype
is the first object in its inheritance so its an "instance of" Object
and nothing else.
B. Thenable objects
"Thenable" objects, with a .then
method, are described in the A+ promise specification on which ES6 promises are based.
Recognition and treatment of thenables allow different software libraries, each using its own Promise constructor code, to deal with promises created by another library created using a different constructor. Simply checking if a promise object is an instance of a library's own "Promise" constructor prevents inter-library usage of promise objects.
The one time a promise implementation needs to deal with a "thenable" object, is when a foreign library promise is used to resolve a promise created by an implementation. The standard method of dealing with this is for the implementation to create a new pair of resolve/reject functions, say resolve2
and reject2
for the promise being resolved, and call the thenable's then
method to pass on it's settled value. In pseudo code:
if promiseA, instance of PromiseA, is resolved with promiseB, instance of PromiseB {
PromiseA code creates new resolve2/reject2 functions for promiseA
and calls the thenable's then method as:
promiseB.then( resolve2, reject2);
}
// ....
If promiseB remains pending, promiseA remains pending;
If promiseB is settled, promiseA becomes fulfilled or rejected with the same value.