I have a basic understanding of Async Await, but I seem to be missing something.
Refer to the code below. I have placed console.log lines throughout to trace the execution. I expect that each console.log should return the token in order. but 'Token1' and 'Token3' return 'undefined' while 'Token2' returns the actual token.
Questions:
- Am I using Async await correctly?
- Am I returning 'credentials.access_token' correctly?
async function GetAuthTokenAsync() {
// Initialize the 2-legged OAuth2 client, set specific scopes and optionally set the `autoRefresh` parameter to true
// if you want the token to auto refresh
var autoRefresh = true; // or false
var oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(
FORGE_CLIENT_ID,
FORGE_CLIENT_SECRET,
["data:read", "data:write"],
autoRefresh
);
oAuth2TwoLegged.authenticate().then(
function (credentials) {
// The `credentials` object contains an access_token that is being used to call the endpoints.
// In addition, this object is applied globally on the oAuth2TwoLegged client that you should use when calling secure endpoints.
console.log("Token2: ", credentials.access_token); //RETURNS THE TOKEN
return credentials.access_token;
},
function (err) {
console.error(err);
}
);
}
async function Token() {
const token = await GetAuthTokenAsync();
console.log("Token1: ", token); //RETURNS 'undefined'
return token;
}
Token().then(AuthToken => console.log('Token3: ', AuthToken)); //RETURNS 'undefined'
GetAuthTokenAsync- yourreturnstatement is inside a callback function forthen