Skip to content

Instantly share code, notes, and snippets.

@bitfishxyz
Created May 5, 2020 01:41
Show Gist options
  • Save bitfishxyz/ac8c7d913ecddf5d33eb2ed8bb65e2c9 to your computer and use it in GitHub Desktop.
Save bitfishxyz/ac8c7d913ecddf5d33eb2ed8bb65e2c9 to your computer and use it in GitHub Desktop.
class MyPromise{
constructor(executor) {
// The initial state of the Promise object should be pending
this.status = "pending";
// Store the value after success or reason after fail
this.value = undefined;
// Define a resolve function
let resolve = result => {
// If the state of a Promise instance has changed before, it should not be changed again.
if(this.status !== "pending") return;
this.status = "resolved";
this.value = result;
}
// Define a resolve function
let reject = reason => {
// If the state of a Promise instance has changed before, it should not be changed again.
if(this.status !== "pending") return;
this.status = "rejected";
this.value = reason;
}
// Even if an exception occurs to the executor function,
// it should be handled within the Promise function,
// not thrown outside the Promise function.
try {
executor(resolve, reject)
} catch(err) {
reject(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment