Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class PromiseX {
- constructor(func) {
- this.status = 'pending';
- this.resolvers = [];
- this.rejecters = [];
- const resolve = (value) => {
- if (this.status !== 'pending') {
- return;
- }
- this.status = 'resolved';
- this.value = value;
- this.resolvers.forEach((resolver) => resolver(value));
- };
- const reject = (value) => {
- if (this.status !== 'pending') {
- return;
- }
- this.status = 'rejected';
- this.value = value;
- this.rejecters.forEach((rejecter) => rejecter(value));
- };
- try {
- func(resolve, reject);
- } catch (e) {
- reject(e);
- }
- this.then = (onFulfilled, onRejected) => {
- return new PromiseX((thenResolve, thenReject) => {
- this.resolvers.push((value) => {
- if (typeof onFulfilled !== 'function') {
- thenResolve(value);
- return;
- }
- try {
- const nextValue = onFulfilled(value);
- if (nextValue instanceof PromiseX) {
- nextValue.then((value) => thenResolve(value));
- } else {
- thenResolve(nextValue);
- }
- } catch (error) {
- thenReject(error);
- }
- });
- this.rejecters.push((value) => {
- if (typeof onRejected !== 'function') {
- thenReject(value);
- return;
- }
- try {
- const nextValue = onRejected(value);
- if (nextValue instanceof PromiseX) {
- nextValue.then((value) => thenResolve(value));
- } else {
- thenResolve(nextValue);
- }
- } catch (error) {
- thenReject(error);
- }
- });
- });
- };
- this.catch = (onError) => this.then(null, onError);
- }
- static resolve = (value) => new PromiseX((resolve) => resolve(value));
- static reject = (value) => new PromiseX((resolve, reject) => reject(value));
- static all = (arrayOfPromises) =>
- new PromiseX((resolve, reject) => {
- const resolved = [];
- arrayOfPromises.forEach((promise) => {
- promise
- .then((value) => {
- resolved.push(value);
- if (resolve.length === arrayOfPromises.length) {
- resolve(resolved);
- }
- })
- .catch(reject);
- });
- });
- static race = (arrayOfPromises) =>
- new PromiseX((resolve, reject) => {
- arrayOfPromises.forEach((promise) => {
- promise.then(resolve).catch(reject);
- });
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement