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

React Promise取值与后端响应处理:如何等待异步结果?

Hey there! Let's figure out why you're getting undefined in your then callback and fix this, plus cover all your questions about handling async operations in React.

First, the root cause of your undefined issue

Look at your api_get function: you're making the axios request and handling its response, but you forgot to return the Promise that axios.get creates. Since functions in JS return undefined by default, when you call api_get().then(...), you're essentially trying to chain a then to nothing—so the callback gets undefined as its argument.

Here's the fixed version of api_get:

const api_get = () => {
  // Return the entire axios Promise chain
  return axios.get(url)
    .then(function(response){
      console.log("after api : ", response.data);
      return response; // This value will be passed to the outer .then()
    });
}

Or using arrow functions for brevity:

const api_get = () => 
  axios.get(url)
    .then(response => {
      console.log("after api : ", response.data);
      return response;
    });

Now, let's answer your other questions:

1. How to handle the backend server's response?

Axios wraps the backend response in an object where the actual data from your server lives in response.data. You can process this data directly in the inner then (like formatting it, picking specific fields) before returning it to the outer callback. Don't forget to handle errors with catch:

const api_get = () => {
  return axios.get(url)
    .then(response => {
      // Process the backend data here if needed
      const processedData = response.data.map(item => ({
        id: item.id,
        name: item.name.toUpperCase()
      }));
      return processedData; // Pass processed data to outer .then()
    })
    .catch(error => {
      console.error("Request failed:", error.response?.data || error.message);
      // Re-throw the error if you want the outer code to handle it
      throw error;
    });
}

2. How to get the value after the pending state ends?

You have two main approaches:

  • Promise chaining with .then(): As we fixed earlier, once your api_get returns a Promise, the outer .then() will fire only when the pending state resolves (the request succeeds), giving you the final value.
  • async/await syntax (more readable for sequential async code): This is a sugar coating over Promises that lets you write async code like sync code. Here's how to use it:
// In a React component or another function
const fetchAndUseData = async () => {
  try {
    const data = await api_get(); // Wait for the Promise to resolve
    console.log("Got data:", data);
    // Use the data here (e.g., update React state)
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
};

// Call the async function
fetchAndUseData();

3. How to wait for async operations to complete in React?

In React components, you'll typically use useEffect to run async code when the component mounts (or when dependencies change), paired with useState to track the request's state (loading, success, error):

import { useEffect, useState } from 'react';

function DataFetchingComponent() {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const responseData = await api_get();
        setData(responseData);
      } catch (err) {
        setError(err.message);
      } finally {
        setIsLoading(false); // Stop loading regardless of success/failure
      }
    };

    fetchData();
  }, []); // Empty array means this runs only once on component mount

  // Render based on the state
  if (isLoading) return <div>Loading data...</div>;
  if (error) return <div>Oops! {error}</div>;

  return (
    <div>
      <h2>Fetched Data:</h2>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

Key takeaways

  • Always return the Promise from your async functions so external code can hook into their completion.
  • Use .then()/.catch() or async/await to handle async results and errors.
  • In React, combine useEffect (for running async code) with useState (for tracking request states) to create a smooth user experience.

内容的提问来源于stack exchange,提问作者박지훈o

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:52:27