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

129
Views
¿Cómo hacer que la pila JS realmente "espere" el final de una función asíncrona?

Estoy aprendiendo cómo funciona JavaScript asíncrono y estoy tratando de imprimir en la consola los números 1 y 2 (en este orden). La función que registra 1 tiene un setTimeout y, como tal, el orden siempre se invierte. Sé por qué sucede esto. Simplemente no sé cómo hacer que funcione como me gustaría. He intentado esto:

 function first(){ setTimeout( ()=>console.log(1), 1000 ) return Promise.resolve(true) } function second(){ console.log(2) } function a(){ first() .then(second()) } console.log("running...") a()

y tambien esto:

 async function first(){ setTimeout( ()=>console.log(1), 2000 ) return true } function second(){ console.log(2) } async function a(){ await first() second() } console.log("running...") a()

Ambos de los cuales imprimen

 running... 2 1

La salida deseada sería

 running... 1 2

¿Qué estoy haciendo mal?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

¿No serían aceptables las devoluciones de llamadas?

 function first(callback) { setTimeout(() => { console.log(1); callback(); }, 2000); } function second() { console.log(2) } // When first is completed, second will run. first(() => second()); console.log("This can run at any time, while we're waiting for our callback.");

about 4 years ago · Juan Pablo Isaza Report

0

Lea acerca de las promesas de Js ( developer.mozilla.org ) aquí, su código funciona

 function first(){ return new Promise((resolve)=>{ console.log('waiting') setTimeout( ()=>{console.log(1); resolve('waiting finished')}, 2000 ) } ); } function second(){ console.log(2) } async function a(){ await first().then(res => console.log(res)) second() } console.log("running...") a()

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!