From f63e1a9662776630a2ec0845499269e6c19f5140 Mon Sep 17 00:00:00 2001 From: Diogo Marciano Date: Sat, 21 Nov 2026 15:45:47 -0300 Subject: [PATCH] Translate "Fetch: Abort" article to Portuguese Co-Authored-By: Claude Sonnet 5 --- 5-network/04-fetch-abort/article.md | 104 ++++++++++++++-------------- 1 file changed, 52 insertions(+), 52 deletions(-) diff --git a/5-network/04-fetch-abort/article.md b/5-network/04-fetch-abort/article.md index eadc5aac2..6eff8b698 100644 --- a/5-network/04-fetch-abort/article.md +++ b/5-network/04-fetch-abort/article.md @@ -1,60 +1,60 @@ # Fetch: Abort -As we know, `fetch` returns a promise. And JavaScript generally has no concept of "aborting" a promise. So how can we cancel an ongoing `fetch`? E.g. if the user actions on our site indicate that the `fetch` isn't needed any more. +Como sabemos, `fetch` retorna uma promessa. E o JavaScript geralmente não tem o conceito de "abortar" uma promessa. Então, como podemos cancelar um `fetch` em andamento? Por exemplo, se as ações do usuário no nosso site indicarem que o `fetch` não é mais necessário. -There's a special built-in object for such purposes: `AbortController`. It can be used to abort not only `fetch`, but other asynchronous tasks as well. +Existe um objeto nativo especial para esse propósito: `AbortController`. Ele pode ser usado para abortar não só `fetch`, mas outras tarefas assíncronas também. -The usage is very straightforward: +O uso é bem direto: -## The AbortController object +## O objeto AbortController -Create a controller: +Cria um controller: ```js let controller = new AbortController(); ``` -A controller is an extremely simple object. +Um controller é um objeto extremamente simples. -- It has a single method `abort()`, -- And a single property `signal` that allows to set event listeners on it. +- Ele tem um único método `abort()`, +- E uma única propriedade `signal`, que permite definir ouvintes de evento nela. -When `abort()` is called: -- `controller.signal` emits the `"abort"` event. -- `controller.signal.aborted` property becomes `true`. +Quando `abort()` é chamado: +- `controller.signal` emite o evento `"abort"`. +- A propriedade `controller.signal.aborted` se torna `true`. -Generally, we have two parties in the process: -1. The one that performs a cancelable operation, it sets a listener on `controller.signal`. -2. The one that cancels: it calls `controller.abort()` when needed. +Em geral, temos duas partes no processo: +1. A que realiza uma operação cancelável, que define um ouvinte em `controller.signal`. +2. A que cancela: ela chama `controller.abort()` quando necessário. -Here's the full example (without `fetch` yet): +Aqui está o exemplo completo (ainda sem `fetch`): ```js run let controller = new AbortController(); let signal = controller.signal; -// The party that performs a cancelable operation -// gets the "signal" object -// and sets the listener to trigger when controller.abort() is called -signal.addEventListener('abort', () => alert("abort!")); +// A parte que realiza uma operação cancelável +// obtém o objeto "signal" +// e define o ouvinte para disparar quando controller.abort() for chamado +signal.addEventListener('abort', () => alert("abortar!")); -// The other party, that cancels (at any point later): -controller.abort(); // abort! +// A outra parte, que cancela (a qualquer momento depois): +controller.abort(); // abortar! -// The event triggers and signal.aborted becomes true +// O evento dispara e signal.aborted se torna true alert(signal.aborted); // true ``` -As we can see, `AbortController` is just a mean to pass `abort` events when `abort()` is called on it. +Como podemos ver, `AbortController` é só um meio de propagar eventos `abort` quando `abort()` é chamado nele. -We could implement the same kind of event listening in our code on our own, without the `AbortController` object. +Poderíamos implementar o mesmo tipo de escuta de eventos no nosso código por conta própria, sem o objeto `AbortController`. -But what's valuable is that `fetch` knows how to work with the `AbortController` object. It's integrated in it. +Mas o que é valioso é que `fetch` sabe como trabalhar com o objeto `AbortController`. Isso está integrado nele. -## Using with fetch +## Usando com fetch -To be able to cancel `fetch`, pass the `signal` property of an `AbortController` as a `fetch` option: +Para conseguir cancelar o `fetch`, passe a propriedade `signal` de um `AbortController` como uma opção do `fetch`: ```js let controller = new AbortController(); @@ -63,22 +63,22 @@ fetch(url, { }); ``` -The `fetch` method knows how to work with `AbortController`. It will listen to `abort` events on `signal`. +O método `fetch` sabe como trabalhar com `AbortController`. Ele vai escutar eventos `abort` em `signal`. -Now, to abort, call `controller.abort()`: +Agora, para abortar, chame `controller.abort()`: ```js controller.abort(); ``` -We're done: `fetch` gets the event from `signal` and aborts the request. +Terminamos: `fetch` recebe o evento de `signal` e aborta a requisição. -When a fetch is aborted, its promise rejects with an error `AbortError`, so we should handle it, e.g. in `try..catch`. +Quando um fetch é abortado, sua promessa rejeita com um erro `AbortError`, então devemos tratá-lo, por exemplo, num `try..catch`. -Here's the full example with `fetch` aborted after 1 second: +Aqui está o exemplo completo com o `fetch` abortado depois de 1 segundo: ```js run async -// abort in 1 second +// aborta em 1 segundo let controller = new AbortController(); setTimeout(() => controller.abort(), 1000); @@ -87,45 +87,45 @@ try { signal: controller.signal }); } catch(err) { - if (err.name == 'AbortError') { // handle abort() - alert("Aborted!"); + if (err.name == 'AbortError') { // trata o abort() + alert("Abortado!"); } else { throw err; } } ``` -## AbortController is scalable +## AbortController é escalável -`AbortController` is scalable. It allows to cancel multiple fetches at once. +`AbortController` é escalável. Ele permite cancelar vários fetches de uma vez. -Here's a sketch of code that fetches many `urls` in parallel, and uses a single controller to abort them all: +Aqui está um esboço de código que busca várias `urls` em paralelo, e usa um único controller para abortar todas elas: ```js -let urls = [...]; // a list of urls to fetch in parallel +let urls = [...]; // uma lista de urls para buscar em paralelo let controller = new AbortController(); -// an array of fetch promises +// um array de promessas de fetch let fetchJobs = urls.map(url => fetch(url, { signal: controller.signal })); let results = await Promise.all(fetchJobs); -// if controller.abort() is called from anywhere, -// it aborts all fetches +// se controller.abort() for chamado de qualquer lugar, +// ele aborta todos os fetches ``` -If we have our own asynchronous tasks, different from `fetch`, we can use a single `AbortController` to stop those, together with fetches. +Se tivermos nossas próprias tarefas assíncronas, diferentes de `fetch`, podemos usar um único `AbortController` para interrompê-las, junto com os fetches. -We just need to listen to its `abort` event in our tasks: +Só precisamos escutar seu evento `abort` nas nossas tarefas: ```js let urls = [...]; let controller = new AbortController(); -let ourJob = new Promise((resolve, reject) => { // our task +let ourJob = new Promise((resolve, reject) => { // nossa tarefa ... controller.signal.addEventListener('abort', reject); }); @@ -134,15 +134,15 @@ let fetchJobs = urls.map(url => fetch(url, { // fetches signal: controller.signal })); -// Wait for fetches and our task in parallel +// Espera os fetches e nossa tarefa em paralelo let results = await Promise.all([...fetchJobs, ourJob]); -// if controller.abort() is called from anywhere, -// it aborts all fetches and ourJob +// se controller.abort() for chamado de qualquer lugar, +// ele aborta todos os fetches e ourJob ``` -## Summary +## Resumo -- `AbortController` is a simple object that generates an `abort` event on its `signal` property when the `abort()` method is called (and also sets `signal.aborted` to `true`). -- `fetch` integrates with it: we pass the `signal` property as the option, and then `fetch` listens to it, so it's possible to abort the `fetch`. -- We can use `AbortController` in our code. The "call `abort()`" -> "listen to `abort` event" interaction is simple and universal. We can use it even without `fetch`. +- `AbortController` é um objeto simples que gera um evento `abort` na sua propriedade `signal` quando o método `abort()` é chamado (e também define `signal.aborted` como `true`). +- `fetch` se integra com ele: passamos a propriedade `signal` como opção, e então `fetch` a escuta, então é possível abortar o `fetch`. +- Podemos usar `AbortController` no nosso código. A interação "chamar `abort()`" -> "escutar o evento `abort`" é simples e universal. Podemos usá-la até mesmo sem `fetch`.