Home > Software engineering >  why my Nodejs / NestJs promise is returning undefined to variable in second function?
why my Nodejs / NestJs promise is returning undefined to variable in second function?

Time:10-13

I have 2 functions. when I called 1st function promise from second function it prints the output correct but my 'newdata' variable in second function is returning undefined value. Please help.

My functions are:

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', //gave the values directly for testing
        password: 'admin123',
        grant_type: 'password',
        client_id: 'admin-cli',
      }),
      {
        headers: { 
          "Content-Type": "application/x-www-form-urlencoded"
        }
      }
      ).then(function(response) {       
        console.log(response.data);     
    }); 
    
  }


  async newKeyToken(data: any){
    const newdata = await this.keycloaktokennew(data);
    if (newdata=="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;
    }
  }

CodePudding user response:

if (newdata=="undefined") should be (!newdata), as in current flow it expect incoming "undefined" from previous function which is undefined because you do not return any information from callback.

    ).then(function(response) {       
        console.log(response.data);     
    });

Additionally you should return data from your promise.

    ).then(function(response) {       
        console.log(response.data);
        return response.data
    });

CodePudding user response:

You need to return the response

then(function(response) {       
        console.log(response.data);
        return response.data;     
    }); 

61

The console will print the result of evaluating an expression. The result of evaluating console.log() is undefined since console.log does not explicitly return something. It has the side effect of printing to the console.

  • Related