Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Why does setTimeOut not work with my recreated promise function?

I tried recreating the Promise class of javascript with the class keyword and function closure, it works with promise functions that returns instantly, but does not work with setTimeOut. I tried adding console.log into the setTimeOut function to check, it does not even print when the time is up. Is it because of the while loop that checks for change of state in myPromise class?

// custom promise function
class MyPromise {
  constructor(func) {
    this.func = func;
  }

  resolveWrapper() {
    var state = 'pending';
    var value = '';

    function myResolve(val) {
      value = val;
      state = 'resolved';
    }

    function myReject(val) {
      value = val;
      state = 'rejected';
    }

    function getStateValue() {
      let stateValue = {
        state: state,
        value: value,
      }
      return stateValue;
    }

    let returnVal = {
      resolve: myResolve,
      reject: myReject,
      getter: getStateValue,
    }

    return returnVal;
  }

  then(nextFunc) {
    let stateValue = this.resolveWrapper();
    let getter = stateValue.getter;
    this.func(stateValue.resolve, stateValue.reject);

    while (getter().state === 'pending') {
      // keep checking
    }
    return nextFunc(getter.value);
  }
}
// test
let newProm = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    console.log('timeout');
    resolve('1');
  }, 1000);
})

let tst = newProm.then((val) => (console.log(val)));

console.log(tst);

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!