-2

I am working on the Zoom API now. I want to send my token from ZOOM API to front-end as a response. However, "token from request" is always printed first and undefined! Then the token from Zoon API" will be followed with the token. How can I make it happen? Thx!

const Newrequest = require("request");

class ZoomController {
  async getInvLink({ request, response }) {
const instructor_id = params.id;
try {
  let tokenRes;
  const code = request.all().code;
  console.log("the code from frontend is ", code);
  const client_id = _something_
  const client_secret = _something_
  var options = {
    method: "POST",
    url: "https://api.zoom.us/oauth/token",
    qs: {
      grant_type: "authorization_code",
      code: code,
      redirect_uri: _something_
    },
    headers: {
      Authorization:
        "Basic " +
        Buffer.from(client_id + ":" + client_secret).toString("base64")
    }
  };

  await Newrequest(options, function(error, res, body) {
    if (error) throw new Error(error);
    tokenRes = JSON.parse(body);
    console.log("token from Zoon API",tokenRes);
  });

  console.log("token from request",tokenRes);
  return response.status(200).send(tokenRes);
} catch (error) {
  console.log(error);
  return response.status(401).send();
}
karel
  • 3,880
  • 31
  • 37
  • 42
  • 1
    you can't just await a function call and expect it to actually wait on it, not knowing whether or not it returns a promise. – Kevin B Sep 23 '20 at 14:20

3 Answers3

0

I have no idea what this api is, but I'm going to make an educated guess that Newrequest doesn't return a promise. So awaiting it isn't actually what you want to do.

What you can do, however, is use some simple code to turn it into a promise:

const tokenRes = await new Promise((resolve, reject) =>  {
    Newrequest(options, function(error, res, body) {
      if (error) reject(error);
      tokenRes = JSON.parse(body);
      console.log("token from Zoon API",tokenRes);
      resolve(tokenRes);
    });
})
TKoL
  • 10,782
  • 1
  • 26
  • 50
0

You would have to listen to an endpoint at something and you will receive the code over there. This is the code you can send to exchange for an access token.

Ralph
  • 219
  • 1
  • 7
0

Please consult this link : https://www.npmjs.com/package/request#promises--asyncawait

You can convert a regular function that takes a callback to return a promise instead with util.promisify()

Example :

Newrequest(options, function(error, res, body) {
    if (error) throw new Error(error);
    tokenRes = JSON.parse(body);
    console.log("token from Zoon API",tokenRes);
});

// to

const util = require('util');

const req = util.promisify(Newrequest)
const data = await req(options)
// ... 

It's a sample code. Please adapt with your needs

Useful course : https://masteringjs.io/tutorials/node/promisify

Request library is deprecated

It would be interesting to use another library.

Alternatives :

crbast
  • 1,750
  • 1
  • 7
  • 16