Skip to content

Introduction callbacks #133

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

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
146 changes: 73 additions & 73 deletions 1-js/11-async/01-callbacks/article.md
Original file line number Diff line number Diff line change
@@ -1,67 +1,67 @@


# Introduction: callbacks
# Introdução: callbacks

```warn header="We use browser methods in examples here"
To demonstrate the use of callbacks, promises and other abstract concepts, we'll be using some browser methods: specifically, loading scripts and performing simple document manipulations.
```warn header="Nós usamos métodos do navegador aqui nos exemplos"
Para demonstrar o uso de callbacks, promises e outros conceitos abstratos, nós vamos usar alguns métodos do navegador: especificamente, carregar scripts e fazer manipulações simples de documentos.

If you're not familiar with these methods, and their usage in the examples is confusing, you may want to read a few chapters from the [next part](/document) of the tutorial.
Se você não está familiarizado com esses métodos, e o uso deles nos exemplos parece confuso, pode ser que você queira ler alguns capítulos da [próxima parte](/document) do tutorial.

Although, we'll try to make things clear anyway. There won't be anything really complex browser-wise.
Mas nós vamos tentar deixar as coisas claras de qualquer jeito. Não vai ter nada muito complexo em relação ao navegador.
```

Many functions are provided by JavaScript host environments that allow you to schedule *asynchronous* actions. In other words, actions that we initiate now, but they finish later.
Muitas funções providas pelo JavaScript permitem que você agende ações *assíncronas*. Em outras palavras, ações que nós iniciamos agora, mas que terminam mais tarde.

For instance, one such function is the `setTimeout` function.
Por exemplo, uma dessas funções é a função `setTimeout`.

There are other real-world examples of asynchronous actions, e.g. loading scripts and modules (we'll cover them in later chapters).
Existem outros exemplos práticos de ações assíncronas, por exemplo: carregar scripts e módulos (nós vamos ver nos capítulos adiante).

Take a look at the function `loadScript(src)`, that loads a script with the given `src`:
Veja a função `loadScript(src)`, que carrega um script com um dado `src`:

```js
function loadScript(src) {
// creates a <script> tag and append it to the page
// this causes the script with given src to start loading and run when complete
// cria uma tag <script> e a anexa à página
// isso faz com que o script com o determinado src comece a carregar e seja executado quando concluído
let script = document.createElement('script');
script.src = src;
document.head.append(script);
}
```

It inserts into the document a new, dynamically created, tag `<script src="…">` with the given `src`. The browser automatically starts loading it and executes when complete.
Ela acrescenta ao documento uma nova, dinamicamente criada, tag `<script src="…">` com o `src` passado. O navegador começa a carregar ele automaticamente e o executa quando terminar.

We can use this function like this:
Podemos usar essa função assim:

```js
// load and execute the script at the given path
// carrega e executa o script no caminho dado
loadScript('/my/script.js');
```

The script is executed "asynchronously", as it starts loading now, but runs later, when the function has already finished.
O script é executado "assincronamente", porque ele começa a carregar agora, mas executa mais tarde, quando a função já terminou.

If there's any code below `loadScript(…)`, it doesn't wait until the script loading finishes.
Se tiver algum código abaixo de `loadScript(…)`, ele não espera até que o script termine de carregar.

```js
loadScript('/my/script.js');
// the code below loadScript doesn't wait for the script loading to finish
// o código embaixo de loadScript não espera o carregamento do script terminar
// ...
```

Let's say we need to use the new script as soon as it loads. It declares new functions, and we want to run them.
Agora, vamos imaginar que queremos usar o novo script assim que ele terminar de carregar. Ele provavelmente declara novas funções, e queremos executar elas.

But if we do that immediately after the `loadScript(…)` call, that wouldn't work:
Mas se nós fizéssemos isso imediatamente depois da chamada `loadScript(…)`, não iria funcionar.

```js
loadScript('/my/script.js'); // the script has "function newFunction() {…}"
loadScript('/my/script.js'); // o script tem "function newFunction() {…}"

*!*
newFunction(); // no such function!
newFunction(); // a função não existe!
*/!*
```

Naturally, the browser probably didn't have time to load the script. So the immediate call to the new function fails. As of now, the `loadScript` function doesn't provide a way to track the load completion. The script loads and eventually runs, that's all. But we'd like to know when it happens, to use new functions and variables from that script.
Naturalmente, o navegador provavelmente não teve tempo de carregar o script. Então a chamada imediata para a nova função falha. Do jeito que está, a função `loadScript` não provê uma maneira de saber quando o carregamento termina. O script carrega e eventualmente é executado, isso é tudo. Mas nós queremos saber quando isso acontece, para podermos usar as novas funções e variáveis daquele script.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sugestão de alteração:

  • Alterar e eventualmente é executado para e é eventualmente executado.

image

Regra "Colocação de advérbio"

https://community.languagetool.org/rule/show/COLOCA%C3%87%C3%83O_ADV%C3%89RBIO?lang=pt


Let's add a `callback` function as a second argument to `loadScript` that should execute when the script loads:
Vamos adicionar uma função `callback` como segundo argumento em `loadScript` que deve executar quando o script terminar de carregar:

```js
function loadScript(src, *!*callback*/!*) {
Expand All @@ -76,19 +76,19 @@ function loadScript(src, *!*callback*/!*) {
}
```

Now if we want to call new functions from the script, we should write that in the callback:
Agora se nós quisermos chamar as novas funções do script, nós podemos fazer isso no callback:

```js
loadScript('/my/script.js', function() {
// the callback runs after the script is loaded
newFunction(); // so now it works
// o callback executa depois que o script termina de carregar
newFunction(); // então agora funciona
...
});
```

That's the idea: the second argument is a function (usually anonymous) that runs when the action is completed.
Esta é a ideia: o segundo argumento é uma função (normalmente anônima) que executa quando a ação termina.

Here's a runnable example with a real script:
Veja um exemplo executável com um script real:

```js run
function loadScript(src, callback) {
Expand All @@ -100,39 +100,39 @@ function loadScript(src, callback) {

*!*
loadScript('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js', script => {
alert(`Cool, the script ${script.src} is loaded`);
alert( _ ); // function declared in the loaded script
alert(`Legal, o script ${script.src} está carregado`);
alert( _ ); // função declarada no script carregado
});
*/!*
```

That's called a "callback-based" style of asynchronous programming. A function that does something asynchronously should provide a `callback` argument where we put the function to run after it's complete.
Isso é chamado de programação assíncrona "baseada em callbacks". A função que faz alguma coisa assincronamente deve prover um argumento `callback` onde nós colocamos a função que vai executar depois que ela estiver completa.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sugestão de alteração:

  • Alterar alguma coisa para algo.

image

Regra "2. Expressões prolixas"

https://community.languagetool.org/rule/show/PT_WORDINESS_REPLACE?lang=pt


Here we did it in `loadScript`, but of course it's a general approach.
Aqui nós fizemos isso em `loadScript`, mas é claro que isso é uma abordagem genérica.

## Callback in callback
## Callback no callback

How can we load two scripts sequentially: the first one, and then the second one after it?
Como poderíamos carregar dois scripts sequencialmente? Carregar um primeiro, e depois o segundo?

The natural solution would be to put the second `loadScript` call inside the callback, like this:
A solução natural seria colocar a segunda chamada de `loadScript` dentro do callback, assim:

```js
loadScript('/my/script.js', function(script) {

alert(`Cool, the ${script.src} is loaded, let's load one more`);
alert(`Legal, ${script.src} foi carregado, vamos carregar mais um`);

*!*
loadScript('/my/script2.js', function(script) {
alert(`Cool, the second script is loaded`);
alert(`Legal, o segundo script foi carregado`);
});
*/!*

});
```

After the outer `loadScript` is complete, the callback initiates the inner one.
Depois que o `loadScript` de fora termina, o callback inicia o `loadScript` de dentro.

What if we want one more script...?
E se nós quisermos mais um script...?

```js
loadScript('/my/script.js', function(script) {
Expand All @@ -141,7 +141,7 @@ loadScript('/my/script.js', function(script) {

*!*
loadScript('/my/script3.js', function(script) {
// ...continue after all scripts are loaded
// ...continua depois que todo os scripts forem carregados
});
*/!*

Expand All @@ -150,13 +150,13 @@ loadScript('/my/script.js', function(script) {
});
```

So, every new action is inside a callback. That's fine for few actions, but not good for many, so we'll see other variants soon.
Então, toda ação nova fica dentro de um callback. Tudo bem para poucas ações, mas não é bom para muitas ações. Por isso nós vamos ver outras variantes em breve.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sugestão de alteração:

  • Alterar dentro de para em.

image

Regra "Dentro de/da(s)/do(s) > em/na(s)/no(s)"

https://community.languagetool.org/rule/show/DENTRO_DE_DA_DAS_DO_DOS_EM_NA_NAS_NO_NOS?lang=pt


## Handling errors
## Tratando erros

In the above examples we didn't consider errors. What if the script loading fails? Our callback should be able to react on that.
No exemplo acima nós não consideramos erros. E se o carregamento do script falhar? Nosso callback deveria ser capaz de reagir a isso.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sugestão de alteração:

  • Alterar ser capaz de para conseguir.

image

Regra "Ser capaz de → Conseguir"

https://community.languagetool.org/rule/show/SER_CAPAZ_DE_CONSEGUIR?lang=pt


Here's an improved version of `loadScript` that tracks loading errors:
Abaixo temos uma versão melhorada do `loadScript` que rastreia os erros de carregamento:

```js
function loadScript(src, callback) {
Expand All @@ -165,39 +165,39 @@ function loadScript(src, callback) {

*!*
script.onload = () => callback(null, script);
script.onerror = () => callback(new Error(`Script load error for ${src}`));
script.onerror = () => callback(new Error(`Erro no carregamento do script ${src}`));
*/!*

document.head.append(script);
}
```

It calls `callback(null, script)` for successful load and `callback(error)` otherwise.
O código acima chama `callback(null, script)` quando o carregamento é feito com sucesso e `callback(error)` caso contrário.

The usage:
Usando a função:
```js
loadScript('/my/script.js', function(error, script) {
if (error) {
// handle error
// tratar o erro
} else {
// script loaded successfully
// script carregado com sucesso
}
});
```

Once again, the recipe that we used for `loadScript` is actually quite common. It's called the "error-first callback" style.
De novo, o padrão que nós usamos para o `loadScript` é bem comum. É chamado de estilo "callback com erro primeiro".

The convention is:
1. The first argument of the `callback` is reserved for an error if it occurs. Then `callback(err)` is called.
2. The second argument (and the next ones if needed) are for the successful result. Then `callback(null, result1, result2…)` is called.
A convenção é:
1. O primeiro argumento do `callback` é reservado para um erro, se algum ocorrer. Então `callback(err)` é chamado.
2. O segundo argumento (e o próximo se for necessário) são para quando houver sucesso. Então `callback(null, result1, result2…)` é chamado.

So the single `callback` function is used both for reporting errors and passing back results.
Assim uma única função `callback` é usada tanto para reportar erros quanto para retornar os resultados.

## Pyramid of Doom
## Pirâmide da Perdição

At first glance, it looks like a viable approach to asynchronous coding. And indeed it is. For one or maybe two nested calls it looks fine.
À primeira vista parece uma maneira viável de programação assíncrona. E realmente é. Para uma ou duas chamadas aninhadas está ok.

But for multiple asynchronous actions that follow one after another, we'll have code like this:
Mas para múltiplas ações assíncronas que seguem uma depois da outra, vamos ter um código como esse:

```js
loadScript('1.js', function(error, script) {
Expand All @@ -216,7 +216,7 @@ loadScript('1.js', function(error, script) {
handleError(error);
} else {
*!*
// ...continue after all scripts are loaded (*)
// ...continua depois que todos os scripts são carregados (*)
*/!*
}
});
Expand All @@ -227,14 +227,14 @@ loadScript('1.js', function(error, script) {
});
```

In the code above:
1. We load `1.js`, then if there's no error...
2. We load `2.js`, then if there's no error...
3. We load `3.js`, then if there's no error -- do something else `(*)`.
No código acima:
1. Carregamos `1.js`, e depois, se não tiver nenhum erro...
2. Carregamos `2.js`, e depois, se não tiver nenhum erro...
3. Carregamos `3.js`, e depois, se não tiver nenhum erro -- faz outra coisa `(*)`.

As calls become more nested, the code becomes deeper and increasingly more difficult to manage, especially if we have real code instead of `...` that may include more loops, conditional statements and so on.
À medida em que as chamadas ficam mais aninhadas, o código vai ficando mais profundo e cada vez mais difícil de gerenciar, especialmente se nós tivermos um código real em vez de `...`, que pode incluir mais laços, condicionais e assim por diante.

That's sometimes called "callback hell" or "pyramid of doom."
Isso é às vezes chamado de "callback hell (inferno dos callbacks)" ou "pyramid of doom (pirâmide da perdição)."

<!--
loadScript('1.js', function(error, script) {
Expand Down Expand Up @@ -262,11 +262,11 @@ loadScript('1.js', function(error, script) {

![](callback-hell.svg)

The "pyramid" of nested calls grows to the right with every asynchronous action. Soon it spirals out of control.
A "pirâmide" de chamadas aninhadas cresce para a direita a cada ação assíncrona e rapidamente sai do controle.

So this way of coding isn't very good.
Então esse jeito de programar não é muito bom.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sugestão de alteração:

  • Alterar muito bom para bom.

image

Regra "2. Expressões prolixas"

https://community.languagetool.org/rule/show/PT_WORDINESS_REPLACE?lang=pt


We can try to alleviate the problem by making every action a standalone function, like this:
Nós podemos tentar diminuir o problema fazendo cada ação ser uma função separada, assim:

```js
loadScript('1.js', step1);
Expand All @@ -293,17 +293,17 @@ function step3(error, script) {
if (error) {
handleError(error);
} else {
// ...continue after all scripts are loaded (*)
// ...continua depois que todos os scripts são carregados (*)
}
}
```

See? It does the same thing, and there's no deep nesting now because we made every action a separate top-level function.
Viu? Isso faz a mesma coisa, e não tem aninhamento profundo agora porque nós transformamos cada ação em uma função de nível superior separada.

It works, but the code looks like a torn apart spreadsheet. It's difficult to read, and you probably noticed that one needs to eye-jump between pieces while reading it. That's inconvenient, especially if the reader is not familiar with the code and doesn't know where to eye-jump.
Funciona, porém o código parece uma planilha dividida. É difícil de ler, e você provavelmente percebeu que precisamos de pular entre as partes do código enquanto estamos lendo ele. Isso é inconveniente, especialmente se o leitor não estiver familiarizado com o código e não souber para onde pular.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sugestão de alteração:

  • Adicionar virgula após a locução porém.

image

Regra "Locuções entre vírgulas: portanto, por exemplo, na verdade"

https://community.languagetool.org/rule/show/VERB_COMMA_CONJUNCTION?lang=pt


Also, the functions named `step*` are all of single use, they are created only to avoid the "pyramid of doom." No one is going to reuse them outside of the action chain. So there's a bit of namespace cluttering here.
Além disso, as funções chamadas `step*` são todas utilizadas apenas uma vez. Elas são criadas apenas pra evitar a "pirâmide da perdição." Ninguém vai reutilizá-las fora da cadeia de ações. Então tem um pouco de bagunça aqui.

We'd like to have something better.
Gostaríamos de ter algo melhor.

Luckily, there are other ways to avoid such pyramids. One of the best ways is to use "promises", described in the next chapter.
Felizmente, existem outras maneiras de evitar essas pirâmides. Uma das melhores maneiras é usar "promises (promessas)", descritas no próximo capítulo.