Node.js中async函数未返回预期数据该如何解决?
解决Node.js中async/await获取API数据返回Promise的问题
你的代码里fetchData()是async函数,所有async函数执行后都会返回一个Promise对象,所以直接赋值给result并打印,得到的就是处于pending状态的Promise。要拿到实际数据,需要等待Promise兑现,以下是几种可行的修改方式:
方式1:用自执行异步函数包裹调用
async function fetchData() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return data; } // 自执行异步函数中使用await获取结果 (async () => { const result = await fetchData(); console.log(result); // 打印API返回的实际数据 })();
方式2:使用Promise的.then()方法
async function fetchData() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return data; } // 通过.then()接收Promise兑现后的结果 fetchData().then(result => { console.log(result); // 打印API返回的实际数据 });
方式3:Node.js顶级作用域直接使用await(Node.js 14.8+支持)
如果你的Node.js版本在14.8及以上,可以直接在顶级作用域使用await:
async function fetchData() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return data; } const result = await fetchData(); console.log(result); // 打印API返回的实际数据
核心逻辑:async函数的返回值必然是Promise,必须通过await(仅能在async函数或顶级作用域使用)或者.then()来获取Promise内部的实际值,不能直接打印async函数的调用结果。
内容的提问来源于stack exchange,提问作者Alfredo Damanik
相关产品推荐
相关产品推荐

