TopLevelAwait (TL01)
1: // dbModule.js
2: const connectionPromise = fetch('/api/databaseConfig')
3: .then(response => response.json());
4:
5: const config = await connectionPromise; // Top-level await!
6: const db = connectToDatabase(config); // Asynchronously connects to the DB
7:
8: export default db; // Export the initialized database connection
9: //In any other module:
10: import db from './dbModule.js';
11: db.query('SELECT * FROM users').then( /* ... */ ); // Use the already initialized db connection directly in other modules
top-level await is a relatively recent feature (ES2022), Browser or Node.js supports it Simplifying Module Initialization:
TopLevelAwait context:
ES6 context:
Comments (
)
)
Link to this page:
http://www.vb-net.com/JavascriptES6/TL01.htm
|
|