Avatar ·

How to get result from async request in JavaScript?

Hello everyone! I'm new to JavaScript and I've encountered a problem that has me completely stumped. I'm trying to get data from an AJAX request and return it from a function, but I can't get it to work. Here's my code: ```javascript function getUserData(userId) { let userData; fetch(`https://api.example.com/users/${userId}`) .then(response => response.json()) .then(data => { userData = data; console.log('Inside then:', userData); // Data exists }); console.log('After fetch:', userData); // undefined return userData; // Always undefined } const user = getUserData(123); console.log('Result:', user); // undefined ``` I understand the problem is related to asynchrony, but I can't figure out how to properly "return" the da