将响应传递给addEventListener内部的函数

时间:2019-07-10 02:43:42

标签: javascript reactjs react-native javascript-events async-await

我正在使用一个API,其中响应位于addEventListener函数内部,我希望在收到响应后将其传递给函数。我想实现以下目标:

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

0 个答案:

没有答案