Created
February 17, 2022 21:22
-
-
Save pablo-rufat/042abe14aa8d70e874d58c33b8a48832 to your computer and use it in GitHub Desktop.
Como lidar com funções assincronas?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Execute com "node asyncawait.js" | |
// O objetivo do script a seguir é perceber os diferentes outcomes a depender de como é tratada uma chamada à um metodo assincrono. | |
// O seguinte metodo tem uma Promise que vai se resolver em um segundo. Depois um boolean é criado e a depender do valor pode retornar 'Eba!' ou lançar um erro. | |
const asyncFunctionWithReject = async () => { | |
await new Promise((r) => setTimeout(r, 1000)); | |
const isTrue = Boolean(Math.round(Math.random())); | |
if (isTrue) { | |
return "Eba!"; | |
} | |
throw Error("Poxa!"); | |
}; | |
const justCall = async () => { | |
// Posiveis saidas: | |
// - O metodo vai chamar asyncFunctionWithReject mas não vai esperar ela finalizar. Então o metodo justCall vai finalizar sem retornar nada (undefined). Após disso, a Promise do metodo asyncFunctionWithReject vai se resolver e, se isTrue === true não acontecera nada (vai fazer o return para um metodo que já finalizou), mas se cair no throw, o applicativo vai mostrar o Error. | |
try { | |
asyncFunctionWithReject(); | |
} catch (e) { | |
return "Caiu no catch!"; | |
} | |
}; | |
const callAndAwait = async () => { | |
// Posiveis saidas: | |
// - O metodo vai chamar asyncFunctionWithReject e vai esperar ela finalizar. Se o metodo asyncFunctionWithReject cair no throw, o try do metodo callAndWait vai capturar o throw e vai entrar no catch, retornando 'Caiu no catch'. Caso nao caia no catch, sera mostrado undefined já que o metodo callAndWait não retorna nada. | |
try { | |
await asyncFunctionWithReject(); | |
} catch (e) { | |
return "Caiu no catch!"; | |
} | |
}; | |
const callAndReturn = async () => { | |
// Posiveis saidas: | |
// O metodo vai retornar diretamente o metodo asyncFunctionWithReject. Como estamos chamando o metodo callAndReturn com await, a Promise do metodo asyncFunctionWithReject sera resolvida na linha console.log(await callAndReturn());. Como em esse lugar não temos catch, se cair no throw vamos receber um Error. | |
try { | |
return asyncFunctionWithReject(); | |
} catch (e) { | |
return "Caiu no catch!"; | |
} | |
}; | |
const callAndAwaitAndReturn = async () => { | |
// O metodo vai esperar a função asyncFunctionWithReject igual que anteriormente em callAndAwait. A diferença é que agora vamos retornar (já que temos o comando return) o string 'Eba!' caso tudo de certo e vamos poder mostrar no console na linha console.log(await callAndReturnAndAwait()); | |
try { | |
return await asyncFunctionWithReject(); | |
// A linha de acima é equivalente a: | |
// const response = await asyncFunctionWithReject(); | |
// return response; | |
} catch (e) { | |
return "Caiu no catch!"; | |
} | |
}; | |
// Função assincrona muito simples | |
const simpleFunction = async () => { | |
await new Promise((r) => setTimeout(r, 1000)); | |
return 'Sou muito simples.'; | |
}; | |
// Caso não tenhamos um try/catch e nenhuma excepção que capturar, AS PALAVRAS CHAVE RETURN E AWAIT SÃO REDUNDANTES já que o return vai retornar a função simpleFuntion que vai ser resolvida na linha console.log(await withoutTryCatch()); | |
const withoutTryCatch = async () => { | |
return await simpleFunction(); | |
// O certo seria: | |
// reutn simpleFunction(); | |
}; | |
// Pode testar cada função descomentando a linha correspondente | |
const main = async () => { | |
console.log(await justCall()); | |
// console.log(await callAndAwait()); | |
// console.log(await callAndReturn()); | |
// console.log(await callAndAwaitAndReturn()); | |
// console.log(await withoutTryCatch()); | |
}; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Show d+ @pablo-rufat o único detalhe seriam as linhas de comentário que poderiam ter uma quebra de linha... 🚀