0

I am using an API where the response is coming inside addEventListener function which I want to pass to a function after getting the response received. I am tying to achieve something as follows:

getToken() {
    var data = JSON.stringify({
        "app_key": "my_app_key",
        "app_secret": "my_app_secret"
    });

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;

    xhr.addEventListener("readystatechange", async function () {
      if (this.readyState === this.DONE) {
        console.log(this.responseText);
        await val = this.responseText;
        this.recieveApiResponse(val);
      }
    });

    xhr.open("POST", "https://tokenized.sandbox........../grant");
    xhr.setRequestHeader("username", "my_username");
    xhr.setRequestHeader("password", "my_password");

    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.send(data);
}

recieveApiResponse(resp) {
    console.log(resp)
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Wahidul Alam
  • 1,216
  • 4
  • 26
  • 56
  • As long as the function is bound correctly, should work fine as-is. What's the actual issue? – Dave Newton Jul 10 '19 at 02:46
  • actual issue is the api response. I only can pass the value if i get the response. As i am not having the response synchronously it passes nothing to the function. – Wahidul Alam Jul 10 '19 at 02:49
  • That doesn't make any sense--you're waiting for done, no? (I haven't done adjacent by hand for... a really long time now, and i don't recall the actual mechanics.) – Dave Newton Jul 10 '19 at 02:59
  • 1
    `this` inside the event handler isn't what you think it is. Should be seeing relevant error because of that when you try to call `this.recieveApiResponse()` – charlietfl Jul 10 '19 at 03:03
  • this is not the actual implementation. I am wondering to achieve something like this. and yes you are right I am getting similar error but no clue how to fix @charlietfl – Wahidul Alam Jul 10 '19 at 03:07
  • `this` is the xhr object so you need to store a reference to the class `this` before entering `xhr.addEventListener` ... as outlined in the duplicate link – charlietfl Jul 10 '19 at 03:11
  • Or use arrow function and use `xhr` instead of `this` for those 2 references – charlietfl Jul 10 '19 at 03:14
  • 1
    And even simpler than using `XMLHttpRequest` is use `fetch()` – charlietfl Jul 10 '19 at 03:15
  • @charlietfl or `async` / `await` + `fetch` – John Ruddell Jul 10 '19 at 03:22

0 Answers0