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

async函数返回Promise {undefined},如何获取外部的resp.data.stats.floor_price?

如何在async函数外部获取异步请求返回的值

问题根源

你的getFloorPrice函数存在两个关键问题:

  1. 函数标记为async,但内部执行axios.get后没有返回这个请求的Promise对象,导致函数默认返回undefined,外部拿到的就是包装了undefined的Promise {undefined}。
  2. .then回调里的await是多余的——resp.data.stats.floor_price是同步可用的数据,不需要额外等待。

修复方案

方案一:用async/await重构(推荐,代码更易读)

把axios的回调写法换成async/await,同时确保函数返回正确的异步结果:

const axios = require('axios').default;

async function getFloorPrice(collection) {
    if (collection === '') {
        console.log("请提供集合名称,即https://opensea.io/collection/后面的部分");
        return;
    }
    try {
        const resp = await axios.get(`https://api.opensea.io/api/v1/collection/${collection}/stats`);
        return resp.data.stats.floor_price;
    } catch (err) {
        console.error(`集合"${collection}"不存在,请确认输入的是https://opensea.io/collection/后面的正确名称`);
        throw err; // 抛出错误,方便外部捕获处理
    }
}

// 外部获取值的两种方式:
// 方式1:在async函数内部用await
async function fetchAndLog() {
    try {
        const floorPrice = await getFloorPrice('boredapeyachtclub');
        console.log(floorPrice); // 这里能拿到正确的地板价
    } catch (err) {
        // 处理错误
    }
}
fetchAndLog();

// 方式2:用.then/.catch链式调用
getFloorPrice('boredapeyachtclub')
    .then(floorPrice => console.log(floorPrice))
    .catch(err => console.error(err));

module.exports = getFloorPrice;

方案二:修复原有的.then/.catch写法

如果坚持用回调风格,需要确保函数返回整个axios请求的Promise链:

const axios = require('axios').default;

function getFloorPrice(collection) {
    if (collection === '') {
        console.log("请提供集合名称,即https://opensea.io/collection/后面的部分");
        return Promise.resolve(undefined);
    }
    // 必须return这个axios请求的Promise
    return axios.get(`https://api.opensea.io/api/v1/collection/${collection}/stats`)
        .then(resp => resp.data.stats.floor_price)
        .catch(err => {
            console.error(`集合"${collection}"不存在,请确认输入的是https://opensea.io/collection/后面的正确名称`);
            throw err;
        });
}

// 外部调用
getFloorPrice('boredapeyachtclub')
    .then(floorPrice => console.log(floorPrice))
    .catch(err => console.error(err));

module.exports = getFloorPrice;

核心注意事项

  • 所有异步函数(包括async标记的函数)返回的永远是Promise对象,外部必须通过await(仅限async函数内部)或.then()来提取实际值。
  • 确保异步函数内部返回的是你需要的异步操作结果,或者完整的Promise链,否则外部会拿到无意义的Promise {undefined}。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 05:06:27