Avatar ·

如何在JavaScript中从异步请求获取结果?

大家好!我是JavaScript新手,遇到了一个让我困惑的问题。我试图从AJAX请求中获取数据并将其从函数中返回,但总是失败。 这是我的代码: ```javascript function getUserData(userId) { let userData; fetch(`https://api.example.com/users/${userId}`) .then(response => response.json()) .then(data => { userData = data; console.log('在then内部:', userData); // 数据存在 }); console.log('在fetch之后:', userData); // undefined return userData; // 总是undefined } const user = getUserData(123); console.log('结果:', user); // undefined ``` 我明白问题与异步有关,但不知道如何正确“返回”数据。我尝试过使用async/await,但仍然得到undefined。请解释如何正确处理异步调用并获取结果。非常感谢详细解答。