Avatar ·

How to get the result of an async request and return it from a function?

Hello everyone! I'm new to JavaScript and I've run into a problem that I can't solve. I'm writing a simple code that makes an AJAX request to an API and tries to return the received data, but I always get undefined. Here's my code:

\n\n
function getUserData(userId) {\n    let userData;\n    \n    $.ajax({\n        url: 'https://api.example.com/users/' + userId,\n        method: 'GET',\n        success: function(response) {\n            userData = response;\n            console.log('Inside success:', userData); // Data is here!\n        }\n    });\n    \n    return userData; // Always undefined\n}\n\nconst result = getUserData(42);\nconsole.log('Outside:', result); // undefined
\n\n

I understand that the problem is with asynchronicity — the getUserData function