Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MyPromise {
- constructor(executor) {
- if (typeof executor !== 'function') {
- throw new Error('Executor function must be a function');
- }
- this.$state = 'PENDING';
- this.$chained = [];
- const resolve = (res) => {
- if (this.$state !== 'PENDING') {
- return;
- }
- this.$state = 'FULFILLED';
- this.$internalValue = res;
- for (const { onFulfilled } of this.$chained) {
- onFulfilled(res);
- }
- };
- const reject = (err) => {
- if (this.$state !== 'PENDING') {
- }
- this.$state = 'REJECTED';
- this.$internalValue = err;
- for (const { onRejected } of this.$chained) {
- onRejected(err);
- }
- };
- try {
- executor(resolve, reject);
- } catch (err) {
- reject(err);
- }
- }
- then(onFulfilled, onRejected) {
- if (this.$state === 'FULFILLED') {
- onFulfilled(this.$internalValue);
- } else if (this.$state === 'REJECTED') {
- onRejected(this.$internalValue);
- } else {
- this.$chained.push({ onFulfilled, onRejected });
- }
- }
- }
- const firstPromise = new MyPromise((resolve, reject) => {
- setTimeout(() => resolve('wubadubdub'), 1000);
- });
- firstPromise.then(successMessage => console.log(`wahoo ${successMessage}`));
Add Comment
Please, Sign In to add comment