async函数返回Promise {undefined},如何获取外部的resp.data.stats.floor_price?
如何在async函数外部获取异步请求返回的值
问题根源
你的getFloorPrice函数存在两个关键问题:
- 函数标记为
async,但内部执行axios.get后没有返回这个请求的Promise对象,导致函数默认返回undefined,外部拿到的就是包装了undefined的Promise {undefined}。 .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
相关产品推荐
相关产品推荐

