Home > Software engineering >  typescript function is not returning the value but it is getting consoled
typescript function is not returning the value but it is getting consoled

Time:01-10

I am pretty new to typescript i have create the function that return the access token when i try consoling it was working fine but it not returing any value when i call from other function Function that return's value

static generateToken = async (user: any, expires: any):Promise<string>
=> {
    try{
      const config: any = await configHelper.getConfigData();
      const conData: string = JSON.parse(config);
      const configdata = JSON.parse(conData);
      const payload = {
        sub: user.contactId,
        iat: moment().unix(),
        exp: expires.unix(),
        user: user,
      };
      console.log('token one',Jwt.sign(payload, configdata.jwt.secret))
      return Jwt.sign(payload, configdata.jwt.secret);
    }catch(err){
      console.log('Error',err)
      return "Error"
    }
      };

Function where we call i have tried putting await in all the possible places but still i gets pending but it is getting consoled

  static createToken = async (userDetails: any) => {
    const config: any = await configHelper.getConfigData();
    const conData: string = JSON.parse(config);
    const configdata = JSON.parse(conData);
    const accessTokenExpires = moment().add(
      configdata.jwt.accessExpirationMinutes,
      "minutes"
    );
    const accessToken = {
      token: this.generateToken(userDetails, accessTokenExpires),
      expires: accessTokenExpires.toDate(),
    };
    console.log('$$$$$$$$$$$$$$',accessToken)
    const refreshTokenExpires = moment().add(
      configdata.jwt.refreshExpirationMinutes,
      "minutes"
    );
    const refreshToken = {
      token: this.refreshTokenGenerate(userDetails, refreshTokenExpires),
      expires: refreshTokenExpires.toDate(),
    };
    return {
      accessToken,
      refreshToken,
    };
  };

CodePudding user response:

generateToken is declared as async. Which means you must await when you call it.

const accessToken = {
  token: await this.generateToken(userDetails, accessTokenExpires),
  //     ^ added await here
  expires: accessTokenExpires.toDate(),
};

CodePudding user response:

I don't see any await at the actual generateToken call. You would need to await there for the code to wait for the promise to resolve.

const accessToken = {
      token: await this.generateToken(userDetails, accessTokenExpires),
      expires: accessTokenExpires.toDate(),
};

I would suggest you understand how async and await work instead of trying to randomly add "await in all possible places" as brute forcing your way like this will only slow you down and cause frustration.

In short,

"async and await make promises easier to write"
async makes a function return a Promise
await makes a function wait for a Promise

  • Related