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

React中axios请求返回pending Promise,如何获取resolved结果?

问题描述

在React应用中使用axios获取API数据,编写了如下axiosGet函数:

function axiosGet(itemid) {
    const promise = axios(withAuth({
        url: `${apiUrl}/items/?itemid=${itemid}`
    }))
    const dataPromise = promise.then((response) => response.data)
    return dataPromise
}

以及调用该函数的getData代码:

const getData = (theitemid) => {
    const itemdata = axiosGet(theitemid)
        .then(data => {
            console.log(data.length);  // 正确打印预期值
            return data.length
        })
        .catch(err => console.log(err))

    console.log(itemdata) // 此时itemdata为:Promise {<pending>}
    return itemdata
}

希望getData返回axiosGet返回的resolved值,但目前它返回的是处于pending状态的Promise,如何等待itemdata完全resolved后再返回?

解决方案

JavaScript异步操作无法直接同步返回最终结果,必须通过异步机制处理,推荐使用async/await语法实现:

  • 修改getData为async函数,内部用await等待异步结果:
const getData = async (theitemid) => {
    try {
        const data = await axiosGet(theitemid);
        console.log(data.length);
        return data.length;
    } catch (err) {
        console.log(err);
        // 根据业务需求返回默认值或抛出错误,示例返回0
        return 0;
    }
}
  • 调用getData的地方也需要用await或.then()获取最终值,比如在React组件的useEffect中:
useEffect(() => {
    const fetchData = async () => {
        const result = await getData(123);
        console.log(result); // 此处拿到resolved后的length值
    };
    fetchData();
}, []);
  • 可简化axiosGet函数,直接返回链式处理后的Promise:
function axiosGet(itemid) {
    return axios(withAuth({
        url: `${apiUrl}/items/?itemid=${itemid}`
    })).then(response => response.data);
}

内容的提问来源于stack exchange,提问作者Woodchuck

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:42:05