13.7. A Promise: states and resolve once
Topics
This question is in
13. Promise from scratchA promise is a small state machine. It starts pending, and it ends either fulfilled with a value or rejected with a reason. Once it has ended, it never changes again: that guarantee is what lets many parts of a program wait on the same promise and all see the same answer. Everything else about promises, then, chaining, await, is built on top of these few rules.
This is the first of six problems that build a promise class step by step. Here, write the core: the class MyPromise in my-promise.js, with its constructor and two read-only properties that let you see inside it.
Signature
class MyPromise {
constructor(executor) // executor(resolve, reject) is called at once
get state() // "pending", "fulfilled" or "rejected"
get value() // the value or the reason; undefined while pending
}executor: a function the constructor calls with two functions,resolve(value)andreject(reason).stateandvalueare getters: they report the promise's state, and cannot change it.
Requirements
new MyPromise(executor)callsexecutoronce, synchronously, before the constructor returns, with two functions:resolveandreject.- A new promise has
state"pending"andvalueundefined. resolve(value)makes it"fulfilled"with that value (the same object);reject(reason)makes it"rejected"with that reason. Any value counts,undefinedand0included.- Only the first call counts. After a promise has settled, every later call to
resolveorrejectis ignored. - If
executorthrows, the promise is rejected with the thrown error. A throw after the promise has settled changes nothing. resolveandrejectwork when called later (after the constructor has returned), and as plain functions passed around, for example tosetTimeout.- Each promise has its own state: settling one never touches another.
- A non-function
executorthrows aTypeError. CallingMyPromisewithoutnewthrows aTypeErrortoo. - Code outside cannot change
stateorvalue: assigning to them does nothing. - The executor's return value is ignored.
Examples
const p = new MyPromise((resolve) => resolve(42));
console.log(p.state, p.value); // "fulfilled" 42const q = new MyPromise((resolve, reject) => {
reject(new Error("no"));
resolve("ignored");
});
console.log(q.state, q.value.message); // "rejected" "no"const r = new MyPromise((resolve) => setTimeout(resolve, 100, "later"));
console.log(r.state); // "pending"
// 100 ms later: r.state is "fulfilled", r.value is "later"const s = new MyPromise(() => { throw new Error("broken"); });
console.log(s.state, s.value.message); // "rejected" "broken"Environment
- Plain JavaScript in a browser page; the tests use the global class
MyPromise. - Do not use the built-in
PromiseinsideMyPromise. then,catch,finallyand following a thenable passed toresolveare out of scope here: in this stageresolvestores whatever it is given. They are problems 13.8 to 13.11.
Hints
resolveis called as a plain function, with no object before the dot. How can it still reach the right promise?- What single check, at the start of settling, makes every call after the first one do nothing?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it