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

163
Views
Esperar dentro de un bucle for dentro de una función asíncrona da un resultado extraño

¿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');

antes de

después

¿Por qué?

¡Gracias!

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

0

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');
about 4 years ago · Juan Pablo Isaza Report

0

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'));
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!