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 1La salida deseada sería
running... 1 2¿Qué estoy haciendo mal?
¿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.");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()