Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda