¿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 = uploadSi 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?