在 TypeScript 等语言中利用 Async/Await 的异步特性时,使用正确的语法至关重要用于错误处理。一个常见的问题是关于在 try...catch 块中放置待等待的变量。
通常认为最佳实践是将变量声明 放置在 try 块并在那里分配它的值。这允许在变量创建的范围内进行错误处理,并确保它始终包含有效值:
try { const createdUser = await this.User.create(userInfo); console.log(createdUser); // business logic goes here } catch (error) { console.error(error); // from creation or business logic }
let createdUser; try { createdUser = await this.User.create(userInfo); } catch (error) { console.error(error); // from creation } if (createdUser) { // user was successfully created console.log(createdUser); // business logic goes here }
try { const createdUser = await this.User.create(userInfo); // user was successfully created console.log(createdUser); // business logic goes here } catch (error) { if (error instanceof CreationError) { console.error(error); // from creation } else { throw error; } }
await this.User.create(userInfo).then(createdUser => { // user was successfully created console.log(createdUser); // business logic goes here }, error => { console.error(error); // from creation });
以上是如何在 TypeScript 中正确使用 Try...Catch 和 Async/Await?的详细内容。更多信息请关注PHP中文网其他相关文章!