`

Custom Promises

Custom Promise constructor function

// Define a custom Promise constructor function
function PromiseCustom(executorFuncArg) {
  this.state = "pending";

  // Call the executor function
  executorFuncArg();
  let returnValue;
}

function promiseExecutor() {
  console.log("Inside custom promise executor");
}

var promiseCustom1 = new PromiseCustom(promiseExecutor);
function PromiseCustom(executorFuncArg) {
  this.state = "pending";

  // Call the executor function
  executorFuncArg(
    (responseArg) => {
      this.state = "fulfilled";
      console.log(
        "Inside resolve function with return value as: ",
        responseArg
      );
    },
    (errorArg) => {
      this.state = "rejected";
      console.log("Inside error function with error value as: ", errorArg);
    }
  );
}

function customPromiseExecutor(resolve, reject) {
  setTimeout(() => {
    resolve("Sample value");
    console.log("Inside promise executor function");
  }, 10000);
}

var promiseCustom1 = new PromiseCustom(customPromiseExecutor);
function customPromiseExecutor(resolve, reject) {
  setTimeout(() => {
    resolve("Sample value");
    console.log("Inside promise executor function");
  }, 10000);
}

function PromiseCustom(executorFuncArg) {
  this.state = "pending";  
  let successCallbackCustom;
  let errorCallbackCustom;

  this.then = (arg1Callback) => {
    successCallbackCustom = arg1Callback
  };

  this.catch = (arg1Callback) => {
    errorCallbackCustom = arg1Callback
  };
  
  // Call the executor function
  executorFuncArg(
    (resolveResponseArg) => {
      this.state = "fulfilled";
      console.log(
        "Inside resolve function with return value as: ",
        responseArg
      );
      successCallbackCustom(resolveResponseArg)
    },
    (errorArg) => {
      this.state = "rejected";
      errorCallbackCustom(responseArg)
      console.log("Inside error function with error value as: ", errorArg);
    }
  );
}

var promiseCustom1 = new PromiseCustom(customPromiseExecutor);

promiseCustom1.then((someValue) => {
  responseValue = someValue;
});

Promises home

Inbuilt Promises

References