You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

  1. No return value from fetchUsers: Async functions return promises, but right now your fetchUsers doesn't return anything—so the promise resolves to undefined. 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!).
  2. Redundant .json() call: You already parse the response to JSON inside fetchUsers, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:55:33