如何将JavaScript Promise代码转换为async/await并修复调用错误
Fixing Your Async/Await Fetch Code
Let's break down what's going wrong with your current code and fix it step by step.
The Issues in Your Current Implementation
- No return value from
fetchUsers: Async functions return promises, but right now yourfetchUsersdoesn't return anything—so the promise resolves toundefined. That's why when you try to call.json()on its result, you get an error (you're trying to invoke a method on nothing!). - Redundant
.json()call: You already parse the response to JSON insidefetchUsers, so there's no need to do it again in the.then()chain.
Corrected Code
First, update the fetchUsers function to return the parsed data. I've also added a check for HTTP errors (since fetch only rejects on network failures, not 404/500 status codes—this is a common gotcha!):
const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1'; const fetchUsers = async () => { const response = await fetch(API_ENDPOINT); // Check if the request was successful if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const data = await response.json(); return data; // This sends the parsed data back as the promise's resolved value };
Now, call the function correctly—since fetchUsers already returns the parsed JSON, you can directly log it in the .then():
fetchUsers() .then(data => console.log(data)) .catch(error => console.error(`ERROR: ${error}`));
Bonus: Using Async/Await Everywhere
If you want to ditch the .then() chain entirely, wrap the call in an async function and use try/catch for error handling:
async function fetchAndLogData() { try { const data = await fetchUsers(); console.log(data); } catch (error) { console.error(`ERROR: ${error}`); } } fetchAndLogData();
That should resolve your error and make the code work as expected!
内容的提问来源于stack exchange,提问作者Yaroslav Kostiv
相关产品推荐
相关产品推荐

