A simple Promise/A+ implementation in TypeScript.
Promise/A+ is a specification for asynchronous JavaScript promises. This project is a simple implementation of the specification in TypeScript. For more information on the specification, see https://promisesaplus.com/.
To install dependencies:
bun install
To run:
bun run dev
To test:
bun run test
Promise can only have 3 status: pending
, fulfilled
, rejected
.
- When in
pending
, can transit tofulfilled
orrejected
. - When in
fulfilled
orrejected
, can't transit to other status && must have value. - When in
rejected
, can't transit tofulfilled
&& must have reason.
- The executor function in constructor takes two arguments,
resolve
andreject
, both are functions. - Constructor is called immediately when PromiseAPlus instance is created.
Most of the time executor is async, e.g.
setTimeout
,fetch
,XMLHttpRequest
, etc.
- Takes an executor function as argument, e.g.
(resolve, reject) => { ... }
- Then call executor function by passing
resolve
andreject
functions as arguments under the context of Promise instance, e.g.executor.call(this, resolve, reject)
- As we pass resolve & reject to executor,
this
context is lost.
Be careful when passing a function as a callback to another function, the
this
context inside the callback is lost.
executor(this.resolve.bind(this), this.reject.bind(this));
then
method takes two arguments,onFulfilled
andonRejected
.then
method will be called when chainingthen
method on Promise instance.
resolve
will be called when executor function is called withresolve
.- Basically it will be called when Promise is fulfilled (change status from pending to fulfilled).
- Loop through
onFulfilledCallbacks
and call each callback withthis.value
as argument.
reject
is similar toresolve
, but it will only be called when Promise is rejected (change status from pending to rejected).
catch
method is a simplythen(undefined, onRejected)
.catch
method will be called when chainingcatch
method on Promise instance.
finally
method is a simplythen(onFinally, onFinally)
.finally
method will be called when chainingfinally
method on Promise instance no matterfulfilled
orrejected
This project was created using bun init
in bun v1.0.21. Bun is a fast all-in-one JavaScript runtime.