Simulating a Network Call with Promises and Async Await
When you're developing web applications, you often need to test how your code handles network calls before connecting to the real API. In this post, we'll look at simulating network calls using Promises and Async/Await in TypeScript—a practical approach to testing your application's network behavior.
Understanding the Basics
Before getting into our implementation, let's review what we're trying to achieve. We want to create a function that mimics a network call by:
- Introducing delay to simulate network latency
- Handling success and error cases
- Using expected TypeScript types
Creating a Mock API Call
interface User {id: number;name: string;email: string;}function mockFetchUser(id: number): Promise<User> {return new Promise((resolve, reject) => {// Simulate network delay (1-3 seconds)const delay = Math.random() * 2000 + 1000;setTimeout(() => {// Simulate 80% success rateif (Math.random() < 0.8) {resolve({id,name: `User ${id}`,email: `user${id}@example.com`});} else {reject(new Error('Network error'));}}, delay);});}
Using Async/Await
Now let's see how we can use this with async/await:
async function getUserData(id: number): Promise<User> {try {const user = await mockFetchUser(id);console.log('User found:', user);return user;} catch (error) {console.error('Error fetching user:', error);throw error;}}// Usage exampleasync function main() {try {const user = await getUserData(1);// Handle successful response} catch (error) {// Handle error}}
Conclusion
Simulating network calls using Promises and Async/Await in TypeScript provides a powerful way to test your application's behavior under different network conditions. This approach allows you to develop and test your error handling logic without depending on actual network requests.
Don't forget to test your code with the real network calls once your api is ready. 😉