Repository navigation
Fetch: Abort #494
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Fetch: Abort #494
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -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: | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Importante: no original esta frase está no imperativo ("Create a controller"), então o verbo deveria ser "Crie", e não "Cria" (que é a 3ª pessoa do presente do indicativo). Sugestão:
Suggested change
Se preferir manter o termo em inglês, basta trocar "Cria" por "Crie" (veja também o comentário na linha 18). |
||||||
|
|
||||||
| ```js | ||||||
| let controller = new AbortController(); | ||||||
| ``` | ||||||
|
|
||||||
| A controller is an extremely simple object. | ||||||
| Um controller é um objeto extremamente simples. | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Opcional: no texto corrido, a palavra "controller" ficou em inglês (também nas linhas 12 e 102). Nos blocos de código o nome da variável
Suggested change
Na linha 102 ficaria: "...e usa um único controlador para abortar todas elas". |
||||||
|
|
||||||
| - 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`. | ||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Importante: o título do artigo continuou em inglês ("Abort"). Como o restante do texto foi traduzido, sugiro traduzir o título também, por exemplo: