Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

260
Views
Await a HTTP GET METHOD Javascript

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...");
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!