Implementing Top-Level Await for Simplified Asynchronous JavaScript
Guidelines on using top-level await to simplify asynchronous code in JavaScript, allowing await usage outside of async functions.
0 likes
7 views
Rule Content
{ "title": "Implementing Top-Level Await for Simplified Asynchronous JavaScript", "description": "Guidelines on using top-level await to simplify asynchronous code in JavaScript, allowing await usage outside of async functions.", "category": "JavaScript Cursor Rules", "rules": [ { "name": "Enable Top-Level Await in ES Modules", "description": "Ensure that top-level await is used exclusively within ES modules to maintain compatibility and proper module behavior.", "pattern": "^(?!.*\\bimport\\b).*\\bawait\\b", "message": "Top-level await should only be used in ES modules. Ensure your file is an ES module by using the 'import' statement or setting the 'type' field to 'module' in your package.json." }, { "name": "Avoid Top-Level Await in CommonJS Modules", "description": "Prevent the use of top-level await in CommonJS modules to avoid unexpected behavior and maintain code consistency.", "pattern": "^(?!.*\\bimport\\b).*\\bawait\\b", "message": "Top-level await is not supported in CommonJS modules. Refactor your code to use async functions or convert your module to an ES module." }, { "name": "Handle Errors with Try/Catch Blocks", "description": "Encourage the use of try/catch blocks around top-level await expressions to handle potential errors gracefully.", "pattern": "(?<!try\\s*\\{)\\s*await\\s+.*", "message": "Wrap top-level await expressions in try/catch blocks to handle errors and prevent unhandled promise rejections." }, { "name": "Avoid Circular Dependencies with Top-Level Await", "description": "Detect and warn against potential circular dependencies when using top-level await to prevent deadlocks and ensure module stability.", "pattern": ".*", "message": "Be cautious of circular dependencies when using top-level await, as they can lead to deadlocks. Review your module imports to ensure they do not form a circular reference." }, { "name": "Optimize Performance with Asynchronous Imports", "description": "Recommend using dynamic imports with top-level await for modules that are not immediately needed to improve application startup time.", "pattern": "await\\s+import\\s*\\(.*\\)", "message": "Consider using dynamic imports with top-level await for modules that are not required at startup to enhance performance." } ] }