I am trying to get a token from a http request and then use that token later in my code. I am looking for a way to use await if possible because I cannot use fetch or other methods. Currently the code still runs async, which is not what I want. removed usernames and passwords for obvious reasons
var msg = 'Starting up...';
console.log(msg);
function Authenticate() {
return new Promise((resolve, reject) => {
console.log("Authenticating...");
var url = "https://google.com";
client_id = "id"
client_secret = "secret"
var XMLHttpRequest = require('xhr2');
var params = "grant_type=password&username=un&password=pw";
var authorizationBasic = btoa(client_id + ':' + client_secret);
var http = new XMLHttpRequest();
http.open("POST", url+"?"+params, true);
http.setRequestHeader("Accept", "application/json");
http.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
http.onreadystatechange = function () {
if (http.readyState === 4) {
console.log(http.status);
//console.log(http.responseText);
var data = http.responseText;
var jsonResponse = JSON.parse(data);
var token = jsonResponse["access_token"];
resolve("token: " + token);
}
else {
reject("error");
}
}
http.send();
})
}
async function doWork(){
console.log("doing work...");
try{
var bearerToken = await Authenticate();
console.log(bearerToken);
}
catch (err){
console.log(err);
}
console.log("work done...");
}
doWork();
console.log("Exiting...");