So I have a function that uses the refresh token I have to get a new access token and I want to use this function before every call that requires an access token.
The first function refreshAccessToken()
makes the request and returns the response including the body that contains the new access token. Now I thought this was enough but I was getting undefined
followed by the actual data and doing some digging I found this question:
which led me to returning the value from this function so the promise resolves fully and using it in another, returnAccessToken()
.
returnAccessToken()
is supposed to take the resolved promise value and return the access token but it behaves unexpectedly. The console.log
line works like a charm and it logs the correct value everytime but when I return the token and try to use it in the function below it, it is undefined again.
api.js
"use strict"
const request = require("request-promise-native");
refreshAccessToken: async function (credentialsObject) {
const options = {
method: "POST",
uri: <refresh token uri>,
resolveWithFullResponse: true,
json: true
};
return await request(options);
},
returnAccessToken: function (auth) {
this.refreshAccessToken(auth)
.then(function (result) {
// This logs the result correctly
console.log(result.body);
return result.body;
}, function (err) {
console.log(err);
});
},
actionRequiringAccessToken: function (auth) {
let tokens = this.returnAccessToken(auth);
// This returns undefined
console.log(tokens);
}
index.js
Also yes I realize that logging here does nothing as I don't currently return a value I just include it because this is how actionThatRequiresAccessToken()
is run in my setup.
"use strict"
const api = require("api");
let auth = {
// Credentials
};
api.actionRequiringAccessToken(auth)
.then(function (data)) {
console.log(data);
}, function (err) {
console.log(err);
}