Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda