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

Axios GET请求返回数据正常,赋值变量后显示Promise pending求助

问题分析与解决方案

核心问题

你遇到的问题本质是异步函数的执行特性:所有async函数的返回值都会被自动包装成Promise,而同步代码会优先于异步回调执行,导致你直接打印变量时,异步请求还未完成,变量要么是Promise { pending },要么是未赋值的undefined。

你的代码问题拆解

  1. 第一段代码:
    getCalendars()是async函数,直接赋值给defaultCalendars时,变量拿到的是未完成的Promise,而非最终的接口数据。console.log(response.data)能正常打印是因为await已经等待请求完成,而外部的console.log(defaultCalendars)是同步执行的,此时异步请求还没结束。

  2. 第二段代码:
    getCalendars().then(...)本身返回的还是Promise,所以defaultCalendars依然是Promise对象。then里的console.log能拿到数据是因为它是异步回调,会在请求完成后执行,但外部的同步console.log先运行,自然打印pending状态的Promise。

  3. 第三段代码:
    run()是异步函数,调用后不会阻塞主线程,后续的console.log(defaultCalendars)会先执行,此时defaultCalendars还未被赋值,所以打印undefined。

正确解决方案

方案1:在异步函数内部处理数据(推荐)

将需要使用数据的逻辑放在异步函数中,确保在请求完成后再执行:

let defaultCalendars;

async function run() {
    try {
        // 直接获取response.data,避免后续再处理response对象
        defaultCalendars = await getCalendars();
        console.log(defaultCalendars); // 这里能正常拿到数据
        // 在这里调用依赖defaultCalendars的业务逻辑
        renderCalendars(defaultCalendars);
    } catch (err) {
        console.error('获取数据失败:', err);
    }
}

async function getCalendars() {
    const response = await axios.get('http://localhost:3000/calendars');
    return response.data; // 返回实际需要的数据
}

run();

方案2:使用.then链式调用处理数据

确保所有依赖数据的逻辑都在then回调中执行:

async function getCalendars() {
    const response = await axios.get('http://localhost:3000/calendars');
    return response.data;
}

getCalendars()
    .then(data => {
        const defaultCalendars = data;
        console.log(defaultCalendars); // 正常打印数据
        // 在这里处理数据逻辑
    })
    .catch(err => console.error('请求失败:', err));

方案3:顶层await(需环境支持)

如果你的代码运行在支持ES模块的环境(如现代浏览器、Node.js ESM),可以直接使用顶层await:

async function getCalendars() {
    const response = await axios.get('http://localhost:3000/calendars');
    return response.data;
}

// 顶层await直接获取数据
const defaultCalendars = await getCalendars();
console.log(defaultCalendars); // 正常打印数据

额外建议

  • 在getCalendars中直接返回response.data,减少后续代码的层级和处理成本;
  • 给异步操作添加错误捕获,避免未处理的Promise rejection;
  • 永远记住:异步操作的结果只能在异步回调(then/await之后)中安全使用,同步代码无法获取异步操作的实时结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:44:50