简体   繁体   English

在 GWT 应用程序中使用本机 JS 进行异步调用

[英]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.我有一个 GWT 应用程序,我必须在其中包含一个 JS function。所以我使用本机接口在我的 JAVA 代码中使用 JS function。

This is my JS function这是我的 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.但问题是,当我通过 response.json() 收到 Promise 响应时,它仍处于待定状态 state,因此它永远不会进入第 6 行。我尝试使用异步,但似乎 GWT 不支持使用异步/等待.

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?有没有一种方法可以在 GWT 中使用异步或在 GWT 中使用 JS,而不是我不会遇到此问题的本机接口?

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();
}

I got my mistake, I used response.json() twice in my code, once to log and once to return.我弄错了,我在代码中使用了两次 response.json() ,一次用于记录,一次用于返回。 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;
    });
  } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM