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

171
Visualizações
How to wait for a state change asynchronously in Javascript

I want to return the state of o from waitState once the state has changed from false to true. I can't see how not to return immediately :

https://jsfiddle.net/msLzovch/1/

o = {
    state: false
}

async function waitState() {

  let timerId = setInterval(checkState, 1000);
  
  function checkState() {
      if (o.state == true) {
          clearInterval(timerId);
      }
  }
  
  return o.state; // wrong here
  
}

function theEnd() {
  o.state = true;
}

setTimeout(theEnd, 5000);

async function main() {
  let state = await waitState();
  alert(state);
}

main();
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your code doesn't work as you expect because there is nothing preventing the funcion waitState() from returning a value immediately. setInterval() will just return an id that will be stored in timerId and o.state is accessible.

But you don't need to have a loop reading the variable, you can override the object's set method:

const o = {
  state: false
}

Object.defineProperty(o, 'state', {
  set: (value) => {
    this.state = value
    // call your custom function
  }
})

o.state = true // your custom function will be called
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use a promise:

o = {
    state: false
}

async function waitState() {
  return new Promise(resolve => {
    let timerId = setInterval(checkState, 1000);
  
    function checkState() {
      if (o.state == true) {
        clearInterval(timerId);
        resolve(o.state);
      }
    }
  });
}

function theEnd() {
  o.state = true;
}

setTimeout(theEnd, 5000);

async function main() {
  let state = await waitState();
  alert(state);
}

main();

about 4 years ago · Juan Pablo Isaza Relatório
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