Skip to main content

Posts

Showing posts from February, 2025

Use async and await judiciously

Async functions are a powerful feature in JavaScript and TypeScript, offering a cleaner, more readable alternative to working directly with Promises. However, it’s easy to overuse them or add unnecessary layers of complexity.  By understanding when and how to use async and await effectively, you can write more concise, efficient, and maintainable code. Let’s explore a common scenario where async and await may be overapplied, and how simplifying the function structure can improve code readability and maintainability without sacrificing intent. Take a look at this function which wraps an async function which deletes an entity form a database: const deleteEntity = async (id: number) => {     return await db.entity.delete({ id }); } You would also await deleteEntity when calling it, resulting in two promises, unnecessarily verbose code and less efficient execution.. Instead of awaiting the promise created in deleteEntity , it can just be returned: const deleteEntity ...

axios-http-builder: An Axios instance builder

axios-http-builder is a n Axios i nstance builder for use on client or server side with common features pre-configured: - Timeout - Cancellation By default, Axios does not configure a timeout or a cancellation timeout. However, axios-http-builder sets both to 2 seconds by default, which remains configurable. axios-http-builder also includes an optional exception handler. Install npm i -save axios-http-builder   Usage To use the default configuration, instantiate the Axios instance with buildHttpClient and then use as normal: import { buildHttpClient } from 'axios-http-builder'; const httpClient = buildHttpClient(); await httpClient.get('https://myservice/entity'); buildHttpClient takes a CreateAxiosDefaults object, so you can use any of Axios' options as normal: import { buildHttpClient } from 'axios-http-builder'; const httpClient = buildHttpClient({ baseURL: 'https://myservice' }); await httpClient.get('/entity'); The axios-http-buil...