How to properly use async/await inside Array.map in TypeScript?
Hi! I'm new to TypeScript and trying to understand asynchronous operations inside the Array.map method.
I have an array of user IDs, and I want to get user data for each ID via API (the fetchUserData function returns a Promise). I wrote this code:
```typescript
const userIds: number[] = [1, 2, 3, 4, 5];
async function fetchUserData(id: number): Promise<{ name: string; age: number }> {
const response = await fetch(`https://api.example.com/users/${id}`);
return response.json();
}
// My attempt
const users = userIds.map(async (id) => {
const userData = await fetchUserData(id);
return userData;
});
console.log(users); // Outputs an array of Promises, not data!
```
The problem is that `users` is an array of `Promise` objects, not the actual data.
No answers yet.
Log in to leave an answer