You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
```warn header="We use browser methods in examples here"
6
-
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.
5
+
```warn header="Nós usamos métodos do navegador aqui nos exemplos"
6
+
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.
7
7
8
-
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.
8
+
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.
9
9
10
-
Although, we'll try to make things clear anyway. There won't be anything really complex browser-wise.
10
+
Mas nós vamos tentar deixar as coisas claras de qualquer jeito. Não vai ter nada muito complexo em relação ao navegador.
11
11
```
12
12
13
-
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.
13
+
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.
14
14
15
-
For instance, one such function is the `setTimeout` function.
15
+
Por exemplo, uma dessas funções é a função `setTimeout`.
16
16
17
-
There are other real-world examples of asynchronous actions, e.g. loading scripts and modules (we'll cover them in later chapters).
17
+
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).
18
18
19
-
Take a look at the function `loadScript(src)`, that loads a script with the given`src`:
19
+
Veja a função `loadScript(src)`, que carrega um script com um dado`src`:
20
20
21
21
```js
22
22
functionloadScript(src) {
23
-
//creates a <script> tag and append it to the page
24
-
//this causes the script with given src to start loading and run when complete
23
+
//cria uma tag <script> e a anexa à página
24
+
//isso faz com que o script com o determinado src comece a carregar e seja executado quando concluído
25
25
let script =document.createElement('script');
26
26
script.src= src;
27
27
document.head.append(script);
28
28
}
29
29
```
30
30
31
-
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.
31
+
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.
32
32
33
-
We can use this function like this:
33
+
Podemos usar essa função assim:
34
34
35
35
```js
36
-
//load and execute the script at the given path
36
+
//carrega e executa o script no caminho dado
37
37
loadScript('/my/script.js');
38
38
```
39
39
40
-
The script is executed "asynchronously", as it starts loading now, but runs later, when the function has already finished.
40
+
O script é executado "assincronamente", porque ele começa a carregar agora, mas executa mais tarde, quando a função já terminou.
41
41
42
-
If there's any code below `loadScript(…)`, it doesn't wait until the script loading finishes.
42
+
Se tiver algum código abaixo de `loadScript(…)`, ele não espera até que o script termine de carregar.
43
43
44
44
```js
45
45
loadScript('/my/script.js');
46
-
//the code below loadScript
47
-
//doesn't wait for the script loading to finish
46
+
//o código embaixo de loadScript
47
+
//não espera o carregamento do script terminar
48
48
// ...
49
49
```
50
50
51
-
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.
51
+
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.
52
52
53
-
But if we do that immediately after the `loadScript(…)` call, that wouldn't work:
53
+
Mas se nós fizéssemos isso imediatamente depois da chamada `loadScript(…)`, não iria funcionar.
54
54
55
55
```js
56
-
loadScript('/my/script.js'); //the script has "function newFunction() {…}"
56
+
loadScript('/my/script.js'); //o script tem "function newFunction() {…}"
57
57
58
58
*!*
59
-
newFunction(); //no such function!
59
+
newFunction(); //a função não existe!
60
60
*/!*
61
61
```
62
62
63
-
Naturally, the browser probably didn't have time to load the script. 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.
63
+
Naturalmente, o navegador provavelmente não teve tempo de carregar o script. Atualmente, a função `loadScript`não oferece uma maneira de rastrear a conclusão do carregamento. O script carrega e eventualmente é executado, e isso é tudo. Mas gostaríamos de saber quando isso acontece, para usar novas funções e variáveis desse script.
64
64
65
-
Let's add a `callback`function as a second argument to `loadScript`that should execute when the script loads:
65
+
Vamos adicionar uma função `callback`como segundo argumento em `loadScript`que deve executar quando o script terminar de carregar:
66
66
67
67
```js
68
68
functionloadScript(src, *!*callback*/!*) {
@@ -77,21 +77,21 @@ function loadScript(src, *!*callback*/!*) {
77
77
}
78
78
```
79
79
80
-
The `onload`event is described in the article <info:onload-onerror#loading-a-script>, it basically executes a function after the script is loaded and executed.
80
+
O evento `onload`é descrito no artigo <info:onload-onerror#loading-a-script>, e basicamente executa uma função após o script ser carregado e executado.
81
81
82
-
Now if we want to call new functions from the script, we should write that in the callback:
82
+
Agora se nós quisermos chamar as novas funções do script, nós podemos fazer isso no callback:
83
83
84
84
```js
85
85
loadScript('/my/script.js', function() {
86
-
//the callback runs after the script is loaded
87
-
newFunction(); //so now it works
86
+
//o callback executa depois que o script termina de carregar
87
+
newFunction(); //então agora funciona
88
88
...
89
89
});
90
90
```
91
91
92
-
That's the idea: the second argument is a function (usually anonymous) that runs when the action is completed.
92
+
Esta é a ideia: o segundo argumento é uma função (normalmente anônima) que executa quando a ação termina.
93
93
94
-
Here's a runnable example with a real script:
94
+
Veja um exemplo executável com um script real:
95
95
96
96
```js run
97
97
functionloadScript(src, callback) {
@@ -103,39 +103,39 @@ function loadScript(src, callback) {
alert( _ ); // _ is a function declared in the loaded script
106
+
alert(`Legal, o script ${script.src}está carregado`);
107
+
alert( _ ); // _ é a função declarada no script carregado
108
108
});
109
109
*/!*
110
110
```
111
111
112
-
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.
112
+
Isso é chamado de programação assíncrona "baseada em callbacks". A função que faz algo assincronamente deve prover um argumento `callback`onde nós colocamos a função que vai executar depois que ela estiver completa.
113
113
114
-
Here we did it in`loadScript`, but of course it's a general approach.
114
+
Aqui nós fizemos isso em`loadScript`, mas é claro que isso é uma abordagem genérica.
115
115
116
-
## Callback in callback
116
+
## Callback no callback
117
117
118
-
How can we load two scripts sequentially: the first one, and then the second one after it?
118
+
Como poderíamos carregar dois scripts sequencialmente? Carregar um primeiro, e depois o segundo?
119
119
120
-
The natural solution would be to put the second `loadScript`call inside the callback, like this:
120
+
A solução natural seria colocar a segunda chamada de `loadScript`dentro do callback, assim:
121
121
122
122
```js
123
123
loadScript('/my/script.js', function(script) {
124
124
125
-
alert(`Cool, the ${script.src}is loaded, let's load one more`);
125
+
alert(`Legal, ${script.src}foi carregado, vamos carregar mais um`);
126
126
127
127
*!*
128
128
loadScript('/my/script2.js', function(script) {
129
-
alert(`Cool, the second script is loaded`);
129
+
alert(`Legal, o segundo script foi carregado`);
130
130
});
131
131
*/!*
132
132
133
133
});
134
134
```
135
135
136
-
After the outer`loadScript`is complete, the callback initiates the inner one.
136
+
Depois que o`loadScript`de fora termina, o callback inicia o `loadScript` de dentro.
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.
156
+
Então, toda ação nova fica em 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.
157
157
158
-
## Handling errors
158
+
## Tratando erros
159
159
160
-
In the above examples we didn't consider errors. What if the script loading fails? Our callback should be able to react on that.
160
+
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.
161
161
162
-
Here's an improved version of `loadScript`that tracks loading errors:
162
+
Abaixo temos uma versão melhorada do `loadScript`que rastreia os erros de carregamento:
163
163
164
164
```js
165
165
functionloadScript(src, callback) {
@@ -168,39 +168,39 @@ function loadScript(src, callback) {
3.We load `3.js`, then if there's no error -- do something else`(*)`.
233
+
No código acima:
234
+
1.Carregamos `1.js`, e depois, se não tiver nenhum erro...
235
+
2.Carregamos `2.js`, e depois, se não tiver nenhum erro...
236
+
3.Carregamos `3.js`, e depois, se não tiver nenhum erro -- faz outra coisa`(*)`.
237
237
238
-
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.
238
+
À 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.
239
239
240
-
That's sometimes called "callback hell" or "pyramid of doom."
240
+
Isso é às vezes chamado de "callback hell (inferno dos callbacks)" ou "pyramid of doom (pirâmide da perdição)."
The "pyramid" of nested calls grows to the right with every asynchronous action. Soon it spirals out of control.
268
+
A "pirâmide" de chamadas aninhadas cresce para a direita a cada ação assíncrona e rapidamente sai do controle.
269
269
270
-
So this way of coding isn't very good.
270
+
Então esse jeito de programar não é muito bom.
271
271
272
-
We can try to alleviate the problem by making every action a standalone function, like this:
272
+
Nós podemos tentar diminuir o problema fazendo cada ação ser uma função separada, assim:
273
273
274
274
```js
275
275
loadScript('1.js', step1);
@@ -296,17 +296,17 @@ function step3(error, script) {
296
296
if (error) {
297
297
handleError(error);
298
298
} else {
299
-
// ...continue after all scripts are loaded (*)
299
+
// ...continua depois que todos os scripts são carregados (*)
300
300
}
301
301
}
302
302
```
303
303
304
-
See? It does the same thing, and there's no deep nesting now because we made every action a separate top-level function.
304
+
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.
305
305
306
-
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.
306
+
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.
307
307
308
-
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.
308
+
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.
309
309
310
-
We'd like to have something better.
310
+
Gostaríamos de ter algo melhor.
311
311
312
-
Luckily, there are other ways to avoid such pyramids. One of the best ways is to use "promises", described in the next chapter.
312
+
Felizmente, existem outras maneiras de evitar essas pirâmides. Uma das melhores maneiras é usar "promises (promessas)", descritas no próximo capítulo.
0 commit comments