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

Node.js/NestJS中Promise在第二个函数返回undefined问题求助

问题原因与修复方案

核心问题

你的keycloaktokennew函数虽然在.then()里打印了response.data,但没有把这个值返回出去。因为.then()回调默认返回undefined,所以整个await this.httpService.axiosRef.post(...).then(...)的结果就是undefined,最终导致newKeyToken里的newdata拿到的是undefined。

另外,newKeyToken里的判断if (newdata=="undefined")是错误的——你要判断的是值为undefined,而不是字符串"undefined",这个判断永远不会触发。

修复方案

方案1:移除.then(),直接用await接收响应(推荐)

既然已经用了async/await,就没必要再混用.then(),代码更简洁清晰:

async keycloaktokennew(data: any): Promise<any> {      
  const response = await this.httpService.axiosRef.post(
    `http://localhost:8080/auth/realms/master/protocol/openid-connect/token`,
    querystring.stringify({
      username: 'stdev',
      password: 'admin123',
      grant_type: 'password',
      client_id: 'admin-cli',
    }),
    {
      headers: { 
        "Content-Type": "application/x-www-form-urlencoded"
      }
    }
  );
  console.log(response.data);
  return response.data; // 明确返回需要的数据
}

方案2:在.then()中返回response.data

如果一定要保留.then(),必须在回调里返回数据:

async keycloaktokennew(data: any): Promise<any> {      
  return await this.httpService.axiosRef.post(
    `http://localhost:8080/auth/realms/master/protocol/openid-connect/token`,
    querystring.stringify({
      username: 'stdev',
      password: 'admin123',
      grant_type: 'password',
      client_id: 'admin-cli',
    }),
    {
      headers: { 
        "Content-Type": "application/x-www-form-urlencoded"
      }
    }
  ).then(function(response) {       
    console.log(response.data);     
    return response.data; // 新增返回语句
  }); 
}

修复newKeyToken的判断逻辑

把字符串判断改成值判断:

async newKeyToken(data: any){
  const newdata = await this.keycloaktokennew(data);
  if (newdata === undefined) { // 改成严格判断undefined
    throw new BadRequestException(INVALID_CREDENTIALS);
  } else {
    console.log("-------------------this is Result needed var-----------------");
    console.log(newdata);
    console.log("-------------------this is Result needed var-----------------");
    return newdata;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:20:28