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

154
Views
Una forma idiomática de verificar una condición después de cada espera

¿Existe una forma idiomática/limpia de verificar una condición después de cada espera en una función asíncrona, luego devolver/lanzar condicionalmente?

Por ejemplo, si tenemos una función asíncrona simple para cargar un archivo en un websocket:

 // readFileChunks is an async generator that returns 4KB of the file in every yield async function upload(input) { for(const file of input.files) { const ws = await openUploadWebsocket(file.name) for await(const chunk of readFileChunks(file, 4096)) { await ws.write(chunk) } await ws.close() } } input.onchange = upload

Si queremos cancelar esta operación cuando el usuario ha vuelto a seleccionar los archivos, probablemente queramos detener la ejecución anterior:

 let previousLock = {stopped: false} async function upload(input) { previousLock.stopped = true const lock = {stopped: false} previousLock = lock for(const file of input.files) { const ws = await openUploadWebsocket(file.name) try { if(lock.stopped) return for await(const chunk of readFileChunks(file, 4096)) { if(lock.stopped) return await ws.write(chunk) if(lock.stopped) return } } finally { await ws.close() } alert("Finished uploading") } } input.onchange = upload

Ahora hay mucho repetitivo porque tenemos que verificar esta condición después de diferentes declaraciones de await . ¿Hay una mejor manera de escribir esto?

about 4 years ago · Juan Pablo Isaza
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!