Pular para o conteúdo
Snippets·Grátis

Snippets de JavaScript e TypeScript

12 snippets de JavaScript (fetch com tempo limite, Promise.allSettled, agrupamento, localStorage) e 8 de TypeScript (type guards, switch exaustivo, as const, satisfies). Os de JavaScript aparecem em arquivos .js e os de TypeScript em arquivos .ts.

Instalação grátis.

Se o PocketCode estiver instalado no seu Android, isto abre a página no app.

Prévia

5 de 20

Fetch JSON with an error checkfetchj

Async function that throws on a non-2xx response and returns the parsed JSON

async function ${1:getData}(${2:url}) {
  const res = await fetch(${2:url});
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json();
}

Fetch with a timeoutfetcht

Abort a request that takes too long

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ${1:5000});
try {
  const res = await fetch(${2:url}, { signal: controller.signal });
  $0
} finally {
  clearTimeout(timer);
}

Sleepsleep

Promise that resolves after a number of milliseconds

const ${1:sleep} = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

Run promises in parallelpall

Await several promises at once and destructure the results

const [${1:a}, ${2:b}] = await Promise.all([${3:loadA()}, ${4:loadB()}]);

Settle all promisespsettled

Wait for every promise and handle successes and failures one by one

const results = await Promise.allSettled(${1:tasks});
for (const r of results) {
  if (r.status === "fulfilled") {
    ${2:console.log(r.value);}
  } else {
    ${3:console.error(r.reason);}
  }
}

Mudanças na 1.0.0

Primeira versão.

Relacionados