DEV Community

Cover image for Concorrência (Código Limpo: Que Bruxaria é Essa?!?! - Parte 8)
ananopaisdojavascript
ananopaisdojavascript

Posted on

3 1

Concorrência (Código Limpo: Que Bruxaria é Essa?!?! - Parte 8)

Use Promessas, nada de "callbacks"

"Callbacks" não são limpos e causam quantidades excessivas de encadeamento. Com o ES2015/ES6, as promessas são um tipo global embutido. Use-as!

Não é recomendável:

import { get } from "request";
import { writeFile } from "fs";

get(
  "https://en.wikipedia.org/wiki/Robert_Cecil_Martin",
  (requestErr, response, body) => {
    if (requestErr) {
      console.error(requestErr);
    } else {
      writeFile("article.html", body, writeErr => {
        if (writeErr) {
          console.error(writeErr);
        } else {
          console.log("File written");
        }
      });
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

É recomendável:

import { get } from "request-promise";
import { writeFile } from "fs-extra";

get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
  .then(body => {
    return writeFile("article.html", body);
  })
  .then(() => {
    console.log("File written");
  })
  .catch(err => {
    console.error(err);
  });
Enter fullscreen mode Exit fullscreen mode

"Async/Await" são ainda mais limpos do que as Promessas

Promessas são uma alternativa bem limpa aos "callbacks", mas ES2015/ES6 nos traz o "async" e o "await", que oferecem uma solução ainda mais limpa. Tudo que você precisa está prefixado na palavra-chave "async" e então você escreve sua lógica de modo imperativo sem uma cadeia de funções "then". Use-os se quiser experimentar as vantagens das funcionalidades do ES2015/ES6 hoje!

Não é recomendável:

import { get } from "request-promise";
import { writeFile } from "fs-extra";

get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
  .then(body => {
    return writeFile("article.html", body);
  })
  .then(() => {
    console.log("File written");
  })
  .catch(err => {
    console.error(err);
  });
Enter fullscreen mode Exit fullscreen mode

É recomendável:

import { get } from "request-promise";
import { writeFile } from "fs-extra";

async function getCleanCodeArticle() {
  try {
    const body = await get(
      "https://en.wikipedia.org/wiki/Robert_Cecil_Martin"
    );
    await writeFile("article.html", body);
    console.log("File written");
  } catch (err) {
    console.error(err);
  }
}

getCleanCodeArticle()
Enter fullscreen mode Exit fullscreen mode

E aí? Gostaram? Até a próxima tradução! 🤗

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay