Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
nildo wants to merge9 commits intojavascript-tutorial:master
base:master
Choose a base branch
Loading
fromnildo:introduction-callbacks
Open
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 73 additions & 73 deletions1-js/11-async/01-callbacks/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff 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, promisesand other abstract concepts, we'll be using some browser methods: specifically, loading scriptsand performing simple document manipulations.
```warn header="Nós usamos métodos do navegador aqui nos exemplos"
Para demonstrar o uso de callbacks, promisese outros conceitos abstratos, nós vamos usar alguns métodos do navegador: especificamente, carregar scriptse 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 byJavaScripthost environments that allow you to schedule *asynchronous* actions. In other words, actions that we initiate now, but they finish later.
Muitas funções providas peloJavaScriptpermitem 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. loadingscriptsand modules (we'll cover them in later chapters).
Existem outros exemplos práticos de ações assíncronas, por exemplo: carregarscriptse módulos (nós vamos ver nos capítulos adiante).

Take alook at the function`loadScript(src)`,that loads a scriptwith the given `src`:
Veja afunção`loadScript(src)`,que carrega um scriptcom um dado `src`:

```js
function loadScript(src) {
//creates a<script>tag and append it to the page
//this causes thescriptwith givensrcto start loading and run when complete
//cria uma tag<script>e a anexa à página
//isso faz com que oscriptcom o determinadosrccomece 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 scriptat the given path
//carrega e executa o scriptno caminho dado
loadScript('/my/script.js');
```

The scriptis 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 thescriptloading finishes.
Se tiver algum código abaixo de`loadScript(…)`,ele não espera até que oscripttermine de carregar.

```js
loadScript('/my/script.js');
//the code belowloadScriptdoesn't wait for thescriptloading to finish
//o código embaixo deloadScriptnão espera o carregamento doscriptterminar
// ...
```

Let's say we need to use the new scriptas soon as it loads. It declares new functions, and we want to run them.
Agora, vamos imaginar que queremos usar o novo scriptassim 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 scripthas "function newFunction() {…}"
loadScript('/my/script.js'); //o scripttem "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 scriptloads 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 scriptcarrega 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:

  • Alterare eventualmente é executado parae é 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 scriptloads:
Vamos adicionar uma função`callback`como segundo argumento em`loadScript`que deve executar quando o scriptterminar 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 thescript,we should write that in the callback:
Agora se nós quisermos chamar as novas funções doscript,nós podemos fazer isso no callback:

```js
loadScript('/my/script.js', function() {
//the callbackruns after thescriptis loaded
newFunction(); //so now it works
//o callbackexecuta depois que oscripttermina 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 realscript:
Veja um exemplo executável com umscript 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 loadedscript
alert(`Legal, o script ${script.src}está carregado`);
alert( _ ); //função declarada noscript carregado
});
*/!*
```

That's called a "callback-based" style of asynchronous programming. Afunction 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". Afunçã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:

  • Alteraralguma coisa paraalgo.

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.

## Callbackin callback
## Callbackno callback

How can we load twoscriptssequentially: the first one, and then the second one after it?
Como poderíamos carregar doisscriptssequencialmente? Carregar um primeiro, e depois o segundo?

Thenaturalsolution would be to put the second`loadScript`call inside thecallback,like this:
A soluçãonaturalseria colocar a segunda chamada de`loadScript`dentro docallback,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 scriptis loaded`);
alert(`Legal, o segundo scriptfoi carregado`);
});
*/!*

});
```

After the outer `loadScript`is complete, the callbackinitiates the inner one.
Depois que o `loadScript`de fora termina, o callbackinicia 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 allscriptsare loaded
// ...continua depois que todo osscriptsforem carregados
});
*/!*

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

So, every new action is inside acallback.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 umcallback.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:

  • Alterardentro de paraem.

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 callbackshould be able to react on that.
No exemplo acima nós não consideramos erros. E se o carregamento do script falhar? Nosso callbackdeveria 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:

  • Alterarser capaz de paraconseguir.

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 {
// scriptloaded successfully
// scriptcarregado 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 allscriptsare loaded (*)
// ...continua depois que todos osscriptssã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 haverealcode 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ódigorealem 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 DownExpand 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:

  • Alterarmuito bom parabom.

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 allscriptsare loaded (*)
// ...continua depois que todos osscriptssã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çãoporé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.

[8]ページ先頭

©2009-2025 Movatter.jp