Cómo hacer tareas asincrónicas como esta:
Quiero tener dos tareas: una imprimiría "foo" después de 1 segundo y la otra imprimiría "barra" después de 2 segundos. Quiero que se inicien al mismo tiempo y se ejecuten de forma asíncrona.
Aquí hay un ejemplo de esto en python:
async def main(): task1 = asyncio.create_task( say_after(1, 'hello')) task2 = asyncio.create_task( say_after(2, 'world')) print(f"started at {time.strftime('%X')}") # Wait until both tasks are completed (should take # around 2 seconds.) await task1 await task2 print(f"finished at {time.strftime('%X')}")¿Cómo hago algo como esto en JavaScript? ¿Uso promesas? No sé cómo funcionan. Soy "nuevo" en javascript
Puede usar then método de promesas js.
function timeout(time_ms) { return new Promise(resolve => setTimeout(resolve, time_ms)); } function main() { timeout(1000).then(() => console.log("hello")) timeout(2000).then(() => console.log("world")) var d = new Date(); var n = d.toLocaleTimeString(); console.log(`started at ${n}`) } main()Puedes hacerlo así:
async function hello() { setTimeout(() => {}, 1000) console.log("hello") } async function world() { setTimeout(() => {}, 2000) console.log("world") } async function main() { await hello() await world() } main()¡Déjame saber si eso funciona para ti!