1

I have a total noob question here but It's killing me. I am building a wrapper for an API and I would like to authenticate and then get back the access token for other requests (note the api is not oAuth).

Below is basically what I am doing:

api.js

function getToken(params) {
 request.post(params, function(err, res, body) {
  return JSON.parse(body).token
 })
}

device.js

 function getDevice(token, id, callback) {
  request.get(..., function(err, res, body){
   callback(err, body)
  })
 }

Now I want to use it like this:

 let token = getToken(myParams) // Should be a String of my token
 let device = getDevice(token, 1234, cb)

As you all know token will be undefined because the request has not returned by the time getDevice is called...

So my question is: how do I make it wait for the token to return before moving on? I will have many other methods that will need this token.

Note: I don't want to add a callback to getToken, I want to stay out of nesting a bunch of callbacks. I have also looked into promises but they often put you in the same issue where all I am doing is adding .then().then()... to everything.

Please, any help would be amazing! Thank you all in advance!

gregwinn
  • 941
  • 1
  • 9
  • 16
  • Use a callback function – Tom O. Mar 08 '18 at 17:36
  • 1
    using `.then()` shouldn't be an issue. If you feel like it's taking up too much space write the functions elsewhere and pass them in to the appropriate `.then` methods. – zfrisch Mar 08 '18 at 17:38
  • 1
    have you looked into [asyc/await?](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9) – Kevin Hoerr Mar 08 '18 at 17:41
  • @KevinHoerr I have not, but this looks like it may solve my issue as long as I get the request to return a promise. I believe request-promise is a thing. – gregwinn Mar 08 '18 at 17:50

1 Answers1

0

Solution with async await (take into account await has to be used into async methods)

function getToken(params) {
 return new Promise((resolve, reject) => {
  request.post(params, function(err, res, body) {
   resolve(JSON.parse(body).token);
  })
 })
}


 function getDevice(token, id, callback) {
  request.get(..., function(err, res, body){
   callback(err, body)
  })
 }

function async myExecutionMethod() {
 let token = await getToken(myParams) // Should be a String of my token
 let device = getDevice(token, 1234, cb)
}

myExecutionMethod();
David Vicente
  • 3,091
  • 1
  • 17
  • 27