Skip to content
Snippets·Free

JavaScript and TypeScript snippets

12 JavaScript snippets (fetch with a timeout, Promise.allSettled, grouping, localStorage) and 8 TypeScript ones (type guards, exhaustive switch, as const, satisfies). The JavaScript ones appear in .js files and the TypeScript ones in .ts files.

Free to install.

If PocketCode is installed on your Android device, this opens the page in the app.

Preview

5 of 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);}
  }
}

Changes in 1.0.0

First version.

Related