为什么Next.js中TypeScript代码的Async函数总是返回空对象?
问题修复方案
核心问题原因
- 异步方法调用未加
await:q1和procurr最终返回的是Promise对象,你未等待异步执行完成就直接JSON.stringify,会将Promise实例序列化为空对象{} this指向错误:用普通函数声明mainObj时,函数内部this不指向类实例,调用this.help会抛出异常,你捕获异常后未做处理,导致逻辑静默失败- 遍历逻辑错误:Hacker News的topstories接口返回的是ID数组,用
for...in遍历拿到的是数组索引而非实际ID值,请求接口会报404错误 - 返回值错误:你注释了处理结果
robj的返回逻辑,直接返回传入的原始参数ob,无法拿到统计后的词频结果
修复步骤
- 在
getStaticProps中调用postClass.q1(obj)时添加await,等待异步逻辑执行完成后再序列化 - 将
mainObj改为箭头函数,继承外层this指向类实例,确保可以正常访问this.help - 将
for...in遍历改为for...of遍历,拿到正确的帖子ID发起接口请求 - 将
mainObj的返回值从ob改为你需要的处理结果robj
修改后代码示例
修复后的procurr方法
private procurr(obj){ const mainObj = async (ob) => { // 改为箭头函数修复this指向 var robj : any = []; var i : number = 0; var total : number = 10; try{ for(const item of ob){ // 改为for...of遍历拿到真实ID let res2 = await axios.get('https://hacker-news.firebaseio.com/v0/item/'+item+'.json'); const obji = res2.data; // axios返回的data直接可用,无需额外await var word : string = this.help.mode(this.help.words(obji.title)); if(word.length > 0){ if(i < total){ robj[i] = this.help.inArr(word, robj) ? this.help.incScore(robj[i]) : {'word': word, 'score':1}; i++; } } } }catch(error){ console.error(error); } return robj; // 返回处理后的结果 } return mainObj(obj); }
修复后的getStaticProps方法
export async function getStaticProps() { const postClass = new Posts(); const res = await axios.get('https://hacker-news.firebaseio.com/v0/topstories.json'); const obj = await res.data; const ob = JSON.stringify(await postClass.q1(obj)); // 添加await等待异步执行完成 return { props: { ob } } }
内容的提问来源于stack exchange,提问作者Chukwu Remijius
相关产品推荐
相关产品推荐

