Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise实现 #61

Open
jyzwf opened this issue Jan 6, 2019 · 0 comments
Open

Promise实现 #61

jyzwf opened this issue Jan 6, 2019 · 0 comments

Comments

@jyzwf
Copy link
Owner

jyzwf commented Jan 6, 2019

const identify = _ => _;

const resolvePromise = (promise2, x, resolve, reject) => {
    if (x === promise2) {
        return reject(new TypeError('循环引用'));
    }

    let called = false;
    if (x instanceof Promise) {
        // x 为promise
        if (x.status === 'pending') {
            x.then(
                y => {
                    resolvePromise(promise2, y, resolve, reject);
                },
                reason => {
                    reject(reason);
                }
            );
        } else {
            x.then(resolve, reject);
        }
    } else if (
        x !== null &&
        (typeof x === 'object' || typeof x === 'function')
    ) {
        try {
            let then = x.then;

            if (typeof then === 'function') {
                then.call(
                    x,
                    y => {
                        if (called) return;
                        called = true;
                        resolvePromise(promise2, y, resolve, reject);
                    },
                    r => {
                        if (called) return;
                        called = true;
                        reject(r);
                    }
                );
            } else {
                resolve(x);
            }
        } catch (e) {
            if (called) return;
            called = true;
            reject(e);
        }
    } else {
        resolve(x);
    }
};

class Promise {
    constructor(exector) {
        this.status = 'pending';
        this.value = undefined;
        this.reason = undefined;

        this.onResolvedCallbacks = [];
        this.onRejectedCallbacks = [];

        const resolve = value => {
            if (value instanceof Promise) {
                value.then(resolve, reject);
            }

            setTimeout(() => {
                if (this.status === 'pending') {
                    this.value = value;
                    this.status = 'fulfilled';

                    this.onResolvedCallbacks.forEach(resolveCb => {
                        // 依次执行then的回调,,
                        resolveCb(this.value);
                    });
                }
            });
        };

        const reject = reason => {
            setTimeout(() => {
                if (this.status === 'pending') {
                    this.reason = reason;
                    this.status = 'rejected';

                    this.onRejectedCallbacks.forEach(rejectedCb => {
                        // 依次执行then的回调,,
                        rejectedCb(this.reason);
                    });
                }
            });
        };

        try {
            exector(resolve, reject);
        } catch (e) {
            reject(e);
        }
    }

    then = (onResolved, onRejected) => {
        let promise2;
        onResolved =
            typeof onResolved === 'function'
                ? onResolved
                : identify(onResolved);
        onRejected =
            typeof onRejected === 'function'
                ? onRejected
                : identify(onRejected);

        if (this.status === 'fulfilled') {
            return (promise2 = new Promise((resolve, reject) => {
                setTimeout(() => {
                    try {
                        let x = onResolved(this.value);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                });
            }));
        } else if (this.status === 'rejected') {
            return (promise2 = new Promise((resolve, reject) => {
                setTimeout(() => {
                    try {
                        let x = onRejected(this.reason);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                });
            }));
        } else {
            return (promise2 = new Promise((resolve, reject) => {
                this.onResolvedCallbacks.push(value => {
                    try {
                        let x = onResolved(value);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                });

                this.onRejectedCallbacks.push(reason => {
                    try {
                        let x = onRejected(reason);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                });
            }));
        }
    };

    valueOf = () => {
        return this.value;
    };

    catch = onRejected => {
        return this.then(null, reason => {
            onRejected(reason);
        });
    };

    finally = fn => {
        return this.then(
            v => {
                setTimeout(fn);
                return v;
            },
            r => {
                setTimeout(fn);
                throw r;
            }
        );
    };

    delay = duration => {
        return this.then(
            value => {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        resolve(value);
                    }, duration);
                });
            },
            reason => {
                new Promise((resolve, reject) => {
                    setTimeout(() => {
                        reject(reason);
                    }, duration);
                });
            }
        );
    };

    static resolve = value => {
        let promise;
        return (promise = new Promise((resolve, reject) => {
            resolvePromise(promise, value, resolve, reject);
        }));
    };

    static reject = reason => {
        return new Promise((resolve, reject) => {
            reject(reason);
        });
    };

    static all = promises => {
        return new Promise((resolve, reject) => {
            let resolveCount = 0;
            let promisesLength = promises.length;

            let resolveValues = new Array(promisesLength);

            promises.forEach((promise, i) => {
                Promise.resolve(promise).then(
                    value => {
                        resolveCount++;
                        resolveValues[i] = value;

                        if (resolveCount === promisesLength) {
                            return resolve(resolveValues);
                        }
                    },
                    reason => {
                        return reject(reason);
                    }
                );
            });
        });
    };

    static race = promises => {
        return new Promise((resolve, reject) => {
            promises.forEach(promise => {
                Promise.resolve(promise).then(
                    value => resolve(value),
                    reason => reject(reason)
                );
            });
        });
    };

    static done = () => {
        return new Promise(() => {});
    };

    static stop = () => {
        return new Promise(() => {});
    };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant