Snippets de JavaScript y TypeScript
12 snippets de JavaScript (fetch con tiempo límite, Promise.allSettled, agrupar, localStorage) y 8 de TypeScript (guardas de tipo, switch exhaustivo, as const, satisfies). Los de JavaScript salen en archivos .js y los de TypeScript en archivos .ts.
Se instala gratis.
Si tienes PocketCode instalado en tu Android, esto abre la página en la app.
Vista previa
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);}
}
}Cambios en la 1.0.0
Primera versión.