跳转到内容
代码片段·免费

JavaScript 与 TypeScript 代码片段

12 个 JavaScript 代码片段(带超时的 fetch、Promise.allSettled、分组、localStorage)和 8 个 TypeScript 代码片段(类型守卫、穷尽 switch、as const、satisfies)。JavaScript 片段出现在 .js 文件中,TypeScript 片段出现在 .ts 文件中。

免费安装。

如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。

预览

20 个中的 5 个

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

1.0.0 的变更

首个版本。

相关