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

175
Views
Cómo esperar un cambio de estado de forma asíncrona en Javascript

Quiero devolver el estado de o de waitState una vez que el estado haya cambiado de falso a verdadero. No puedo ver cómo no volver inmediatamente:

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 answers
Answer question

0

Su código no funciona como esperaba porque no hay nada que impida que la waitState() devuelva un valor inmediatamente. setInterval() simplemente devolverá una identificación que se almacenará en timerId y se podrá acceder a o.state .

Pero no necesita tener un ciclo que lea la variable, puede anular el método de configuración del objeto:

 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 Report

0

Puedes usar una promesa:

 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 Report
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!