Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const delay = (callback) => setTimeout(callback, 0);
- const STATEMAP = {
- PENDING: 0,
- FULFILLED: 1,
- REJECTED: 2,
- }
- class _Promise {
- constructor(callback) {
- this._state = STATEMAP.PENDING;
- this._worker = callback;
- this._handlers = [];
- this._resolve = (value) => {
- this._value = value;
- this._state = STATEMAP.FULFILLED;
- this._handlers.forEach((obj) => {
- this._runHandler(obj.onFulfilled, obj.onRejected);
- });
- };
- this._reject = (error) => {
- this._error = error;
- this._state = STATEMAP.REJECTED;
- this._handlers.forEach((obj) => {
- this._runHandler(obj.onFulfilled, obj.onRejected);
- });
- }
- this._run();
- }
- _run() {
- if (this._worker) {
- try {
- this._worker(this._resolve, this._reject);
- } catch (err) {
- this._reject(err);
- }
- }
- }
- _runHandler(onFulfilled, onRejected) {
- if (this._state === STATEMAP.PENDING) {
- this._handlers.push({onFulfilled, onRejected});
- } else {
- if (this._state === STATEMAP.FULFILLED) {
- onFulfilled(this._value);
- } else if (this._state === STATEMAP.REJECTED) {
- onRejected(this._error);
- }
- }
- }
- then(onSucceeded, onFailed) {
- const self = this;
- const callback = (resolve, reject) => delay(() => {
- self._runHandler((value) => {
- try {
- if (onSucceeded) {
- resolve(onSucceeded(value));
- } else {
- resolve(value);
- }
- } catch (e) {
- reject(e);
- }
- }, (error) => {
- try {
- if (onFailed) {
- reject(onFailed(error));
- } else {
- reject(error);
- }
- } catch (e) {
- reject(e);
- }
- });
- });
- return new _Promise(callback);
- }
- catch(onFailed) {
- this._onRejected = onFailed;
- const self = this;
- const callback = (resolve, reject) => delay(() => {
- self._runHandler(() => {},
- (error) => {
- try {
- if (onFailed) {
- reject(onFailed(error));
- } else {
- reject(error);
- }
- } catch (e) {
- reject(e);
- }
- });
- });
- return new _Promise(callback);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement