Ayush Patwari
Ayush Patwari

Reputation: 63

make async call using native JS in GWT app

I have a GWT app in which I have to include an JS function. So I am using the native interface to use the JS function in my JAVA code.

This is my JS function

function fetchToken() {
  return fetch(URL, { method: "POST" })
    .then(function(response) {
      console.log(response.json());
      return response.json();
    })
    .then(function(data) {
      return data.secret;
    });
  }  

But the problem with this is when I receive the Promise response via response.json(), it is still in pending state, so it never goes to line 6. I tried using async but it seems like GWT does not support using async/await.

Is there a way I can use async in GWT or any other way to use JS in GWT other than native interface in which I do not face this issue?

Upvotes: 0

Views: 269

Answers (2)

Ayush Patwari
Ayush Patwari

Reputation: 63

I got my mistake, I used response.json() twice in my code, once to log and once to return. I realised I can only use it once in my code. Removing the log fixed my code.

function fetchToken() {
  return fetch(URL, { method: "POST" })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      return data.secret;
    });
  } 

Upvotes: 0

Nawaz Pasha
Nawaz Pasha

Reputation: 11

function makeAsyncRequest() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      // Request was successful. Do something with the response.
      console.log(xhr.responseText);
    }
  };
  xhr.open("GET", "http://example.com/api/endpoint", true);
  xhr.send();
}

Upvotes: 1

Related Questions