diff --git a/1-js/11-async/08-async-await/01-rewrite-async/solution.md b/1-js/11-async/08-async-await/01-rewrite-async/solution.md index 3337ef3c4..fa8598e3f 100644 --- a/1-js/11-async/08-async-await/01-rewrite-async/solution.md +++ b/1-js/11-async/08-async-await/01-rewrite-async/solution.md @@ -1,5 +1,5 @@ -The notes are below the code: +As notas estão abaixo do código: ```js run async function loadJson(url) { // (1) @@ -17,11 +17,11 @@ loadJson('https://javascript.info/no-such-user.json') .catch(alert); // Error: 404 (4) ``` -Notes: +Notas: -1. The function `loadJson` becomes `async`. -2. All `.then` inside are replaced with `await`. -3. We can `return response.json()` instead of awaiting for it, like this: +1. A função `loadJson` se torna `async`. +2. Todos os `.then` dentro dela são substituídos por `await`. +3. Podemos fazer `return response.json()` em vez de esperar por ele com `await`, assim: ```js if (response.status == 200) { @@ -29,5 +29,5 @@ Notes: } ``` - Then the outer code would have to `await` for that promise to resolve. In our case it doesn't matter. -4. The error thrown from `loadJson` is handled by `.catch`. We can't use `await loadJson(…)` there, because we're not in an `async` function. + Então o código externo teria que usar `await` para essa promessa ser resolvida. No nosso caso, não faz diferença. +4. O erro lançado por `loadJson` é tratado pelo `.catch`. Não podemos usar `await loadJson(…)` ali, porque não estamos dentro de uma função `async`. diff --git a/1-js/11-async/08-async-await/01-rewrite-async/task.md b/1-js/11-async/08-async-await/01-rewrite-async/task.md index 0c31737da..b8e726a23 100644 --- a/1-js/11-async/08-async-await/01-rewrite-async/task.md +++ b/1-js/11-async/08-async-await/01-rewrite-async/task.md @@ -1,7 +1,7 @@ -# Rewrite using async/await +# Reescreva usando async/await -Rewrite this example code from the chapter using `async/await` instead of `.then/catch`: +Reescreva este código de exemplo do capítulo usando `async/await` em vez de `.then/catch`: ```js run function loadJson(url) { diff --git a/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md b/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md index aa462dbf7..fd6094544 100644 --- a/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md +++ b/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md @@ -1,5 +1,5 @@ -There are no tricks here. Just replace `.catch` with `try..catch` inside `demoGithubUser` and add `async/await` where needed: +Não tem nenhum truque aqui. Só substitua o `.catch` por `try..catch` dentro de `demoGithubUser` e adicione `async/await` onde for necessário: ```js run class HttpError extends Error { @@ -19,29 +19,29 @@ async function loadJson(url) { } } -// Ask for a user name until github returns a valid user +// Pede um nome de usuário até o github retornar um usuário válido async function demoGithubUser() { let user; while(true) { - let name = prompt("Enter a name?", "iliakan"); + let name = prompt("Digite um nome:", "iliakan"); try { user = await loadJson(`https://api.github.com/users/${name}`); - break; // no error, exit loop + break; // sem erro, sai do laço } catch(err) { if (err instanceof HttpError && err.response.status == 404) { - // loop continues after the alert - alert("No such user, please reenter."); + // o laço continua depois do alert + alert("Esse usuário não existe, digite de novo."); } else { - // unknown error, rethrow + // erro desconhecido, relança throw err; } } } - alert(`Full name: ${user.name}.`); + alert(`Nome completo: ${user.name}.`); return user; } diff --git a/1-js/11-async/08-async-await/02-rewrite-async-2/task.md b/1-js/11-async/08-async-await/02-rewrite-async-2/task.md index 13d625d2a..a24d760b4 100644 --- a/1-js/11-async/08-async-await/02-rewrite-async-2/task.md +++ b/1-js/11-async/08-async-await/02-rewrite-async-2/task.md @@ -1,9 +1,9 @@ -# Rewrite "rethrow" with async/await +# Reescreva o "relançamento" com async/await -Below you can find the "rethrow" example. Rewrite it using `async/await` instead of `.then/catch`. +Abaixo você pode encontrar o exemplo de "relançamento". Reescreva-o usando `async/await` em vez de `.then/catch`. -And get rid of the recursion in favour of a loop in `demoGithubUser`: with `async/await` that becomes easy to do. +E se livre da recursão, usando um laço em `demoGithubUser`: com `async/await` isso fica fácil de fazer. ```js run class HttpError extends Error { @@ -25,18 +25,18 @@ function loadJson(url) { }); } -// Ask for a user name until github returns a valid user +// Pede um nome de usuário até o github retornar um usuário válido function demoGithubUser() { - let name = prompt("Enter a name?", "iliakan"); + let name = prompt("Digite um nome:", "iliakan"); return loadJson(`https://api.github.com/users/${name}`) .then(user => { - alert(`Full name: ${user.name}.`); + alert(`Nome completo: ${user.name}.`); return user; }) .catch(err => { if (err instanceof HttpError && err.response.status == 404) { - alert("No such user, please reenter."); + alert("Esse usuário não existe, digite de novo."); return demoGithubUser(); } else { throw err; diff --git a/1-js/11-async/08-async-await/03-async-from-regular/solution.md b/1-js/11-async/08-async-await/03-async-from-regular/solution.md index 7e2ab597e..bea206c86 100644 --- a/1-js/11-async/08-async-await/03-async-from-regular/solution.md +++ b/1-js/11-async/08-async-await/03-async-from-regular/solution.md @@ -1,7 +1,7 @@ -That's the case when knowing how it works inside is helpful. +Esse é um caso em que saber como funciona por dentro ajuda. -Just treat `async` call as promise and attach `.then` to it: +Basta tratar a chamada `async` como uma promessa e anexar `.then` a ela: ```js run async function wait() { await new Promise(resolve => setTimeout(resolve, 1000)); @@ -10,7 +10,7 @@ async function wait() { } function f() { - // shows 10 after 1 second + // mostra 10 depois de 1 segundo *!* wait().then(result => alert(result)); */!* diff --git a/1-js/11-async/08-async-await/03-async-from-regular/task.md b/1-js/11-async/08-async-await/03-async-from-regular/task.md index ca7c186ff..d19278081 100644 --- a/1-js/11-async/08-async-await/03-async-from-regular/task.md +++ b/1-js/11-async/08-async-await/03-async-from-regular/task.md @@ -1,7 +1,7 @@ -# Call async from non-async +# Chame async a partir de não-async -We have a "regular" function called `f`. How can you call the `async` function `wait()` and use its result inside of `f`? +Temos uma função "comum" chamada `f`. Como você pode chamar a função `async` `wait()` e usar o resultado dela dentro de `f`? ```js async function wait() { @@ -11,10 +11,10 @@ async function wait() { } function f() { - // ...what should you write here? - // we need to call async wait() and wait to get 10 - // remember, we can't use "await" + // ...o que você deveria escrever aqui? + // precisamos chamar a wait() async e esperar para obter o 10 + // lembre-se, não podemos usar "await" } ``` -P.S. The task is technically very simple, but the question is quite common for developers new to async/await. +P.S. A tarefa é tecnicamente bem simples, mas a pergunta é bem comum entre desenvolvedores novos no async/await. diff --git a/1-js/11-async/08-async-await/04-promise-all-failure/solution.md b/1-js/11-async/08-async-await/04-promise-all-failure/solution.md index 9fda8e000..3a463b613 100644 --- a/1-js/11-async/08-async-await/04-promise-all-failure/solution.md +++ b/1-js/11-async/08-async-await/04-promise-all-failure/solution.md @@ -1,52 +1,52 @@ -The root of the problem is that `Promise.all` immediately rejects when one of its promises rejects, but it do nothing to cancel the other promises. +A raiz do problema é que o `Promise.all` rejeita imediatamente quando uma das suas promessas é rejeitada, mas ele não faz nada para cancelar as outras promessas. -In our case, the second query fails, so `Promise.all` rejects, and the `try...catch` block catches this error.Meanwhile, other promises are *not affected* - they independently continue their execution. In our case, the third query throws an error of its own after a bit of time. And that error is never caught, we can see it in the console. +No nosso caso, a segunda consulta falha, então o `Promise.all` rejeita, e o bloco `try...catch` captura esse erro. Enquanto isso, as outras promessas *não são afetadas* - elas continuam a execução de forma independente. No nosso caso, a terceira consulta lança um erro próprio depois de um tempo. E esse erro nunca é capturado, podemos ver isso no console. -The problem is especially dangerous in server-side environments, such as Node.js, when an uncaught error may cause the process to crash. +O problema é especialmente perigoso em ambientes do lado do servidor, como o Node.js, quando um erro não capturado pode fazer o processo ser encerrado. -How to fix it? +Como corrigir isso? -An ideal solution would be to cancel all unfinished queries when one of them fails. This way we avoid any potential errors. +Uma solução ideal seria cancelar todas as consultas não finalizadas quando uma delas falha. Dessa forma, evitamos qualquer erro em potencial. -However, the bad news is that service calls (such as `database.query`) are often implemented by a 3rd-party library which doesn't support cancellation. Then there's no way to cancel a call. +Porém, a má notícia é que chamadas de serviço (como `database.query`) são frequentemente implementadas por uma biblioteca de terceiros que não suporta cancelamento. Nesse caso, não há como cancelar uma chamada. -As an alternative, we can write our own wrapper function around `Promise.all` which adds a custom `then/catch` handler to each promise to track them: results are gathered and, if an error occurs, all subsequent promises are ignored. +Como alternativa, podemos escrever nossa própria função que envolve o `Promise.all` e adiciona um tratador `then/catch` personalizado a cada promessa para rastreá-las: os resultados são reunidos e, se ocorrer um erro, todas as promessas seguintes são ignoradas. ```js function customPromiseAll(promises) { return new Promise((resolve, reject) => { const results = []; let resultsCount = 0; - let hasError = false; // we'll set it to true upon first error + let hasError = false; // vamos deixar true no primeiro erro promises.forEach((promise, index) => { promise .then(result => { - if (hasError) return; // ignore the promise if already errored + if (hasError) return; // ignora a promessa se já deu erro results[index] = result; resultsCount++; if (resultsCount === promises.length) { - resolve(results); // when all results are ready - successs + resolve(results); // quando todos os resultados estão prontos - sucesso } }) .catch(error => { - if (hasError) return; // ignore the promise if already errored - hasError = true; // wops, error! - reject(error); // fail with rejection + if (hasError) return; // ignora a promessa se já deu erro + hasError = true; // opa, erro! + reject(error); // falha com rejeição }); }); }); } ``` -This approach has an issue of its own - it's often undesirable to `disconnect()` when queries are still in the process. +Essa abordagem tem um problema próprio - geralmente não é desejável fazer `disconnect()` enquanto as consultas ainda estão em andamento. -It may be important that all queries complete, especially if some of them make important updates. +Pode ser importante que todas as consultas se completem, especialmente se algumas delas fazem atualizações importantes. -So we should wait until all promises are settled before going further with the execution and eventually disconnecting. +Então deveríamos esperar até que todas as promessas sejam estabelecidas antes de seguir com a execução e, por fim, desconectar. -Here's another implementation. It behaves similar to `Promise.all` - also resolves with the first error, but waits until all promises are settled. +Aqui está outra implementação. Ela se comporta de forma parecida com o `Promise.all` - também rejeita com o primeiro erro, mas espera até que todas as promessas sejam estabelecidas. ```js function customPromiseAllWait(promises) { @@ -80,16 +80,16 @@ function customPromiseAllWait(promises) { } ``` -Now `await customPromiseAllWait(...)` will stall the execution until all queries are processed. +Agora `await customPromiseAllWait(...)` vai suspender a execução até que todas as consultas sejam processadas. -This is a more reliable approach, as it guarantees a predictable execution flow. +Essa é uma abordagem mais confiável, já que garante um fluxo de execução previsível. -Lastly, if we'd like to process all errors, we can use either use `Promise.allSettled` or write a wrapper around it to gathers all errors in a single [AggregateError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError) object and rejects with it. +Por fim, se quisermos processar todos os erros, podemos usar o `Promise.allSettled` ou escrever uma função que o envolve e reúne todos os erros em um único objeto [AggregateError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError) e rejeita com ele. ```js -// wait for all promises to settle -// return results if no errors -// throw AggregateError with all errors if any +// espera todas as promessas serem estabelecidas +// retorna os resultados se não houver erros +// lança AggregateError com todos os erros, se houver function allOrAggregateError(promises) { return Promise.allSettled(promises).then(results => { const errors = []; @@ -104,7 +104,7 @@ function allOrAggregateError(promises) { }); if (errors.length > 0) { - throw new AggregateError(errors, 'One or more promises failed'); + throw new AggregateError(errors, 'Uma ou mais promessas falharam'); } return values; diff --git a/1-js/11-async/08-async-await/04-promise-all-failure/task.md b/1-js/11-async/08-async-await/04-promise-all-failure/task.md index 74571c43e..e7d72094b 100644 --- a/1-js/11-async/08-async-await/04-promise-all-failure/task.md +++ b/1-js/11-async/08-async-await/04-promise-all-failure/task.md @@ -1,17 +1,17 @@ -# Dangerous Promise.all +# Promise.all perigoso -`Promise.all` is a great way to parallelize multiple operations. It's especially useful when we need to make parallel requests to multiple services. +O `Promise.all` é uma ótima forma de paralelizar múltiplas operações. É especialmente útil quando precisamos fazer requisições em paralelo para vários serviços. -However, there's a hidden danger. We'll see an example in this task and explore how to avoid it. +Porém, existe um perigo escondido. Vamos ver um exemplo nessa tarefa e explorar como evitá-lo. -Let's say we have a connection to a remote service, such as a database. +Digamos que temos uma conexão com um serviço remoto, como um banco de dados. -There're two functions: `connect()` and `disconnect()`. +Existem duas funções: `connect()` e `disconnect()`. -When connected, we can send requests using `database.query(...)` - an async function which usually returns the result but also may throw an error. +Quando conectados, podemos enviar requisições usando `database.query(...)` - uma função async que geralmente retorna o resultado, mas também pode lançar um erro. -Here's a simple implementation: +Aqui está uma implementação simples: ```js let database; @@ -28,21 +28,21 @@ function disconnect() { database = null; } -// intended usage: +// uso pretendido: // connect() // ... -// database.query(true) to emulate a successful call -// database.query(false) to emulate a failed call +// database.query(true) para simular uma chamada bem-sucedida +// database.query(false) para simular uma chamada que falha // ... // disconnect() ``` -Now here's the problem. +Agora aqui está o problema. -We wrote the code to connect and send 3 queries in parallel (all of them take different time, e.g. 100, 200 and 300ms), then disconnect: +Escrevemos o código para conectar e enviar 3 consultas em paralelo (todas elas levam tempos diferentes, por exemplo 100, 200 e 300ms), e então desconectar: ```js -// Helper function to call async function `fn` after `ms` milliseconds +// Função auxiliar para chamar a função async `fn` depois de `ms` milissegundos function delay(fn, ms) { return new Promise((resolve, reject) => { setTimeout(() => fn().then(resolve, reject), ms); @@ -54,8 +54,8 @@ async function run() { try { await Promise.all([ - // these 3 parallel jobs take different time: 100, 200 and 300 ms - // we use the `delay` helper to achieve this effect + // esses 3 trabalhos em paralelo levam tempos diferentes: 100, 200 e 300 ms + // usamos o auxiliar `delay` para conseguir esse efeito *!* delay(() => database.query(true), 100), delay(() => database.query(false), 200), @@ -63,7 +63,7 @@ async function run() { */!* ]); } catch(error) { - console.log('Error handled (or was it?)'); + console.log('Erro tratado (ou será que foi?)'); } disconnect(); @@ -72,8 +72,8 @@ async function run() { run(); ``` -Two of these queries happen to be unsuccessful, but we're smart enough to wrap the `Promise.all` call into a `try..catch` block. +Duas dessas consultas acabam não tendo sucesso, mas somos espertos o bastante para envolver a chamada do `Promise.all` em um bloco `try..catch`. -However, this doesn't help! This script actually leads to an uncaught error in console! +Porém, isso não ajuda! Esse script na verdade leva a um erro não capturado no console! -Why? How to avoid it? \ No newline at end of file +Por quê? Como evitar isso? \ No newline at end of file diff --git a/1-js/11-async/08-async-await/article.md b/1-js/11-async/08-async-await/article.md index e679b1c4c..9308d5121 100644 --- a/1-js/11-async/08-async-await/article.md +++ b/1-js/11-async/08-async-await/article.md @@ -1,10 +1,10 @@ # Async/await -There's a special syntax to work with promises in a more comfortable fashion, called "async/await". It's surprisingly easy to understand and use. +Existe uma sintaxe especial para trabalhar com promessas de uma forma mais confortável, chamada "async/await". É surpreendentemente fácil de entender e usar. -## Async functions +## Funções async -Let's start with the `async` keyword. It can be placed before a function, like this: +Vamos começar com a palavra-chave `async`. Ela pode ser colocada antes de uma função, assim: ```js async function f() { @@ -12,9 +12,9 @@ async function f() { } ``` -The word "async" before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically. +A palavra "async" antes de uma função significa uma coisa simples: a função sempre retorna uma promessa. Outros valores são automaticamente envolvidos em uma promessa resolvida. -For instance, this function returns a resolved promise with the result of `1`; let's test it: +Por exemplo, esta função retorna uma promessa resolvida com o resultado `1`; vamos testar: ```js run async function f() { @@ -24,7 +24,7 @@ async function f() { f().then(alert); // 1 ``` -...We could explicitly return a promise, which would be the same: +...Poderíamos retornar explicitamente uma promessa, o que daria no mesmo: ```js run async function f() { @@ -34,20 +34,20 @@ async function f() { f().then(alert); // 1 ``` -So, `async` ensures that the function returns a promise, and wraps non-promises in it. Simple enough, right? But not only that. There's another keyword, `await`, that works only inside `async` functions, and it's pretty cool. +Então, o `async` garante que a função retorne uma promessa, e envolve valores que não são promessas nela. Simples o suficiente, certo? Mas não é só isso. Existe outra palavra-chave, `await`, que funciona apenas dentro de funções `async`, e é bem interessante. ## Await -The syntax: +A sintaxe: ```js -// works only inside async functions +// funciona apenas dentro de funções async let value = await promise; ``` -The keyword `await` makes JavaScript wait until that promise settles and returns its result. +A palavra-chave `await` faz o JavaScript esperar até que a promessa seja estabelecida e retorna o resultado dela. -Here's an example with a promise that resolves in 1 second: +Aqui está um exemplo com uma promessa que é resolvida em 1 segundo: ```js run async function f() { @@ -56,7 +56,7 @@ async function f() { }); *!* - let result = await promise; // wait until the promise resolves (*) + let result = await promise; // espera até que a promessa seja resolvida (*) */!* alert(result); // "done!" @@ -65,50 +65,50 @@ async function f() { f(); ``` -The function execution "pauses" at the line `(*)` and resumes when the promise settles, with `result` becoming its result. So the code above shows "done!" in one second. +A execução da função "pausa" na linha `(*)` e retoma quando a promessa é estabelecida, com `result` se tornando o resultado dela. Então o código acima mostra "done!" em um segundo. -Let's emphasize: `await` literally suspends the function execution until the promise settles, and then resumes it with the promise result. That doesn't cost any CPU resources, because the JavaScript engine can do other jobs in the meantime: execute other scripts, handle events, etc. +Vamos reforçar: o `await` literalmente suspende a execução da função até que a promessa seja estabelecida, e então a retoma com o resultado da promessa. Isso não custa nenhum recurso de CPU, porque o motor do JavaScript pode fazer outros trabalhos nesse meio tempo: executar outros scripts, tratar eventos, etc. -It's just a more elegant syntax of getting the promise result than `promise.then`. And, it's easier to read and write. +É só uma sintaxe mais elegante de obter o resultado da promessa do que o `promise.then`. E é mais fácil de ler e escrever. -````warn header="Can't use `await` in regular functions" -If we try to use `await` in a non-async function, there would be a syntax error: +````warn header="Não dá para usar `await` em funções comuns" +Se tentarmos usar `await` em uma função que não seja `async`, teremos um erro de sintaxe: ```js run function f() { let promise = Promise.resolve(1); *!* - let result = await promise; // Syntax error + let result = await promise; // Erro de sintaxe */!* } ``` -We may get this error if we forget to put `async` before a function. As stated earlier, `await` only works inside an `async` function. +Podemos ter esse erro se esquecermos de colocar `async` antes de uma função. Como dito antes, o `await` só funciona dentro de uma função `async`. ```` -Let's take the `showAvatar()` example from the chapter and rewrite it using `async/await`: +Vamos pegar o exemplo do `showAvatar()` do capítulo e reescrevê-lo usando `async/await`: -1. We'll need to replace `.then` calls with `await`. -2. Also we should make the function `async` for them to work. +1. Vamos precisar substituir as chamadas `.then` por `await`. +2. Também precisamos tornar a função `async` para que funcionem. ```js run async function showAvatar() { - // read our JSON + // lê nosso JSON let response = await fetch('/article/promise-chaining/user.json'); let user = await response.json(); - // read github user + // lê o usuário do github let githubResponse = await fetch(`https://api.github.com/users/${user.name}`); let githubUser = await githubResponse.json(); - // show the avatar + // mostra o avatar let img = document.createElement('img'); img.src = githubUser.avatar_url; img.className = "promise-avatar-example"; document.body.append(img); - // wait 3 seconds + // espera 3 segundos await new Promise((resolve, reject) => setTimeout(resolve, 3000)); img.remove(); @@ -119,24 +119,24 @@ async function showAvatar() { showAvatar(); ``` -Pretty clean and easy to read, right? Much better than before. +Bem limpo e fácil de ler, não é? Bem melhor do que antes. -````smart header="Modern browsers allow top-level `await` in modules" -In modern browsers, `await` on top level works just fine, when we're inside a module. We'll cover modules in article . +````smart header="Navegadores modernos permitem `await` de nível superior em módulos" +Em navegadores modernos, o `await` em nível superior funciona perfeitamente bem, quando estamos dentro de um módulo. Vamos abordar módulos no artigo . -For instance: +Por exemplo: ```js run module -// we assume this code runs at top level, inside a module +// supomos que esse código roda em nível superior, dentro de um módulo let response = await fetch('/article/promise-chaining/user.json'); let user = await response.json(); console.log(user); ``` -If we're not using modules, or [older browsers](https://caniuse.com/mdn-javascript_operators_await_top_level) must be supported, there's a universal recipe: wrapping into an anonymous async function. +Se não estivermos usando módulos, ou se [navegadores mais antigos](https://caniuse.com/mdn-javascript_operators_await_top_level) precisarem ser suportados, existe uma receita universal: envolver tudo em uma função async anônima. -Like this: +Assim: ```js (async () => { @@ -148,10 +148,10 @@ Like this: ```` -````smart header="`await` accepts \"thenables\"" -Like `promise.then`, `await` allows us to use thenable objects (those with a callable `then` method). The idea is that a third-party object may not be a promise, but promise-compatible: if it supports `.then`, that's enough to use it with `await`. +````smart header="`await` aceita \"thenables\"" +Assim como o `promise.then`, o `await` nos permite usar objetos thenable (aqueles com um método `then` chamável). A ideia é que um objeto de terceiros pode não ser uma promessa, mas ser compatível com promessas: se ele suporta `.then`, isso já é suficiente para usá-lo com `await`. -Here's a demo `Thenable` class; the `await` below accepts its instances: +Aqui está uma classe `Thenable` de demonstração; o `await` abaixo aceita instâncias dela: ```js run class Thenable { @@ -160,13 +160,13 @@ class Thenable { } then(resolve, reject) { alert(resolve); - // resolve with this.num*2 after 1000ms + // resolve com this.num*2 depois de 1000ms setTimeout(() => resolve(this.num * 2), 1000); // (*) } } async function f() { - // waits for 1 second, then result becomes 2 + // espera 1 segundo, então o resultado se torna 2 let result = await new Thenable(1); alert(result); } @@ -174,11 +174,11 @@ async function f() { f(); ``` -If `await` gets a non-promise object with `.then`, it calls that method providing the built-in functions `resolve` and `reject` as arguments (just as it does for a regular `Promise` executor). Then `await` waits until one of them is called (in the example above it happens in the line `(*)`) and then proceeds with the result. +Se o `await` recebe um objeto que não é uma promessa, mas tem `.then`, ele chama esse método fornecendo as funções nativas `resolve` e `reject` como argumentos (assim como faz para um executor de `Promise` normal). Então o `await` espera até que uma delas seja chamada (no exemplo acima isso acontece na linha `(*)`) e então prossegue com o resultado. ```` -````smart header="Async class methods" -To declare an async class method, just prepend it with `async`: +````smart header="Métodos async de classe" +Para declarar um método async de classe, basta colocar `async` antes dele: ```js run class Waiter { @@ -191,16 +191,16 @@ class Waiter { new Waiter() .wait() - .then(alert); // 1 (this is the same as (result => alert(result))) + .then(alert); // 1 (isso é o mesmo que (result => alert(result))) ``` -The meaning is the same: it ensures that the returned value is a promise and enables `await`. +O significado é o mesmo: garante que o valor retornado seja uma promessa e habilita o `await`. ```` -## Error handling +## Tratamento de erros -If a promise resolves normally, then `await promise` returns the result. But in the case of a rejection, it throws the error, just as if there were a `throw` statement at that line. +Se uma promessa é resolvida normalmente, então `await promise` retorna o resultado. Mas, no caso de uma rejeição, ele lança o erro, exatamente como se houvesse um comando `throw` naquela linha. -This code: +Este código: ```js async function f() { @@ -210,7 +210,7 @@ async function f() { } ``` -...is the same as this: +...é o mesmo que isso: ```js async function f() { @@ -220,9 +220,9 @@ async function f() { } ``` -In real situations, the promise may take some time before it rejects. In that case there will be a delay before `await` throws an error. +Em situações reais, a promessa pode levar algum tempo antes de ser rejeitada. Nesse caso, vai haver um atraso antes do `await` lançar um erro. -We can catch that error using `try..catch`, the same way as a regular `throw`: +Podemos capturar esse erro usando `try..catch`, da mesma forma que um `throw` normal: ```js run async function f() { @@ -239,7 +239,7 @@ async function f() { f(); ``` -In the case of an error, the control jumps to the `catch` block. We can also wrap multiple lines: +No caso de um erro, o controle salta para o bloco `catch`. Também podemos envolver várias linhas: ```js run async function f() { @@ -248,7 +248,7 @@ async function f() { let response = await fetch('/no-user-here'); let user = await response.json(); } catch(err) { - // catches errors both in fetch and response.json + // captura erros tanto no fetch quanto no response.json alert(err); } } @@ -256,33 +256,33 @@ async function f() { f(); ``` -If we don't have `try..catch`, then the promise generated by the call of the async function `f()` becomes rejected. We can append `.catch` to handle it: +Se não tivermos `try..catch`, então a promessa gerada pela chamada da função async `f()` se torna rejeitada. Podemos adicionar `.catch` para tratá-la: ```js run async function f() { let response = await fetch('http://no-such-url'); } -// f() becomes a rejected promise +// f() se torna uma promessa rejeitada *!* f().catch(alert); // TypeError: failed to fetch // (*) */!* ``` -If we forget to add `.catch` there, then we get an unhandled promise error (viewable in the console). We can catch such errors using a global `unhandledrejection` event handler as described in the chapter . +Se esquecermos de adicionar o `.catch` ali, então temos um erro de promessa não tratado (visível no console). Podemos capturar esses erros usando um tratador global do evento `unhandledrejection`, como descrito no capítulo . -```smart header="`async/await` and `promise.then/catch`" -When we use `async/await`, we rarely need `.then`, because `await` handles the waiting for us. And we can use a regular `try..catch` instead of `.catch`. That's usually (but not always) more convenient. +```smart header="`async/await` e `promise.then/catch`" +Quando usamos `async/await`, raramente precisamos do `.then`, porque o `await` cuida da espera para nós. E podemos usar um `try..catch` normal em vez de `.catch`. Isso geralmente é (mas nem sempre) mais conveniente. -But at the top level of the code, when we're outside any `async` function, we're syntactically unable to use `await`, so it's a normal practice to add `.then/catch` to handle the final result or falling-through error, like in the line `(*)` of the example above. +Mas no nível superior do código, quando estamos fora de qualquer função `async`, não conseguimos usar `await` sintaticamente, então é uma prática normal adicionar `.then/catch` para tratar o resultado final ou algum erro que não foi tratado, como na linha `(*)` do exemplo acima. ``` -````smart header="`async/await` works well with `Promise.all`" -When we need to wait for multiple promises, we can wrap them in `Promise.all` and then `await`: +````smart header="`async/await` funciona bem com `Promise.all`" +Quando precisamos esperar por várias promessas, podemos envolvê-las em `Promise.all` e então usar `await`: ```js -// wait for the array of results +// espera pelo array de resultados let results = await Promise.all([ fetch(url1), fetch(url2), @@ -290,22 +290,22 @@ let results = await Promise.all([ ]); ``` -In the case of an error, it propagates as usual, from the failed promise to `Promise.all`, and then becomes an exception that we can catch using `try..catch` around the call. +No caso de um erro, ele se propaga normalmente, da promessa que falhou para o `Promise.all`, e então se torna uma exceção que podemos capturar usando `try..catch` ao redor da chamada. ```` -## Summary +## Resumo -The `async` keyword before a function has two effects: +A palavra-chave `async` antes de uma função tem dois efeitos: -1. Makes it always return a promise. -2. Allows `await` to be used in it. +1. Faz com que ela sempre retorne uma promessa. +2. Permite que o `await` seja usado dentro dela. -The `await` keyword before a promise makes JavaScript wait until that promise settles, and then: +A palavra-chave `await` antes de uma promessa faz o JavaScript esperar até que a promessa seja estabelecida, e então: -1. If it's an error, an exception is generated — same as if `throw error` were called at that very place. -2. Otherwise, it returns the result. +1. Se for um erro, uma exceção é gerada — o mesmo que se `throw error` fosse chamado naquele exato lugar. +2. Caso contrário, retorna o resultado. -Together they provide a great framework to write asynchronous code that is easy to both read and write. +Juntas, elas fornecem uma ótima estrutura para escrever código assíncrono que é fácil tanto de ler quanto de escrever. -With `async/await` we rarely need to write `promise.then/catch`, but we still shouldn't forget that they are based on promises, because sometimes (e.g. in the outermost scope) we have to use these methods. Also `Promise.all` is nice when we are waiting for many tasks simultaneously. +Com `async/await`, raramente precisamos escrever `promise.then/catch`, mas ainda assim não devemos esquecer que eles são baseados em promessas, porque às vezes (por exemplo, no escopo mais externo) precisamos usar esses métodos. Além disso, o `Promise.all` é ótimo quando estamos esperando por várias tarefas simultaneamente.