Skip to content

Instantly share code, notes, and snippets.

@abrjagad
Created February 3, 2022 20:32
Show Gist options
  • Select an option

  • Save abrjagad/e23f99a1850da7d0533f5669d9d9cb20 to your computer and use it in GitHub Desktop.

Select an option

Save abrjagad/e23f99a1850da7d0533f5669d9d9cb20 to your computer and use it in GitHub Desktop.

Revisions

  1. abrjagad created this gist Feb 3, 2022.
    58 changes: 58 additions & 0 deletions promise polyfill.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    class Prom {
    constructor(promiseCallback) {
    this.state = "pending";
    this.value = undefined;
    this.calledResolve = false;
    this.calledReject = false;
    this.innerResolve = () => {};
    this.innerReject = () => {};
    promiseCallback(this.resolved.bind(this), this.rejected.bind(this));
    }

    resolved(value) {
    this.calledResolve = true;
    this.value = value;
    this.then(this.innerResolve);
    // debugger;
    }

    rejected(value) {
    this.calledReject = true;
    this.value = value;
    this.fail(this.innerReject);
    }

    then(cb) {
    if (this.calledResolve) {
    this.innerResolve(this.value);
    return;
    }
    this.innerResolve = cb;
    return this;
    }

    fail(cb) {
    if (this.calledReject) {
    this.innerReject(this.value);
    return;
    }
    this.innerReject = cb;
    return this;
    }
    }

    const promise = new Prom((resolve, reject) => {
    setTimeout(() => {
    resolve("We did it!");
    }, 1000);
    });

    promise.then((response) => {
    console.log(response);
    });
    promise.then((response) => {
    console.log(response, "ave");
    });
    promise.fail((error) => {
    console.log(error);
    });