¿Puede alguien ayudarme a explicarme por qué se comporta de esta manera?
Que yo sepa, agregar la línea await sleep(1) no debería afectar el flujo de código en este caso. Sin embargo, lo hace.
function sleep(time) { return new Promise((r) => setTimeout(r, time)); } async function test(target) { const ids = { a: ['a1', 'a2'], b: ['b3', 'b4'] }[target]; for (id of ids) { console.log('X.', target, id); // await sleep(1); console.log('Y.', target, id); } } test('a'); test('b');¿Por qué?
¡Gracias!
Intente usar for (const id of ids) { . Sin const o let , está definiendo id en el ámbito global.
function sleep(time) { return new Promise((r) => setTimeout(r, time)); } async function test(target) { const ids = { a: ['a1', 'a2'], b: ['b3', 'b4'] }[target]; for (const id of ids) { console.log('X.', target, id); await sleep(1); console.log('Y.', target, id); } } test('a'); test('b');No está esperando que finalice test('a') .
Cuando se alcanza test('b') , test('a') todavía se está ejecutando (porque es una función asíncrona). Si desea que termine antes de iniciar el otro, use .then() :
test('a').then(()=>test('b'));