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!