Safe Error Handling
安全错误处理
安全なエラー処理
Always wrap await calls in a try/catch block. In TypeScript, the error object in the catch block is of type unknown, so type guards are necessary.
始终将 await 调用包装在 try/catch 块中。在 TypeScript 中,catch 块中的错误对象类型为 unknown,因此需要类型保护。
常に await 呼び出しを try/catch ブロックで囲んでください。TypeScriptでは、catchブロック内のエラーオブジェクトは unknown 型であるため、型ガードが必要です。
async function fetchData(): Promise<Data | null> {
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('Network response was not ok');
return await response.json();
} catch (error) {
if (error instanceof Error) {
console.error('Fetch error:', error.message);
} else {
console.error('Unknown error:', error);
}
return null;
}
}
Parallel Execution
并行执行
並列実行
Avoid "waterfall" requests where independent promises await each other sequentially. Use Promise.all to run them concurrently.
避免“瀑布式”请求,即独立的 Promise 相互顺序等待。使用 Promise.all 并发运行它们。
独立したPromiseが互いに順次待機する「ウォーターフォール」リクエストは避けてください。Promise.all を使用してそれらを並行して実行します。
Sequential (Slow)
const user = await getUser(id);
const posts = await getPosts(id);
// Takes time(getUser) + time(getPosts)
Concurrent (Fast)
const [user, posts] = await Promise.all([
getUser(id),
getPosts(id)
]);
// Takes max(time(getUser), time(getPosts))
References
参考资料
参考文献
- MDN Web Docs. (n.d.). async function. Retrieved from developer.mozilla.org MDN Web Docs. (n.d.). async function. 取自 developer.mozilla.org MDN Web Docs. (n.d.). async function. 取得元 developer.mozilla.org
- TypeScript Documentation. (n.d.). Promise Types. Retrieved from typescriptlang.org TypeScript 文档. (n.d.). Promise 类型。 取自 typescriptlang.org TypeScript ドキュメント. (n.d.). Promise 型。 取得元 typescriptlang.org