【问题标题】:Value of Variable within Function NOT Changing when using If Statement in HTTP GET Request在 HTTP GET 请求中使用 If 语句时函数内变量的值不会改变
【发布时间】:2021-11-04 10:48:13
【问题描述】:

我有一个变量叫

let idStatus = '';

我需要我的 getValues 函数返回 true,并使用此变量来确定它返回 true 还是 false。

 function getValues(){
 
 let idStatus = '';

  let getValuesUrl = 'https://something.something.com/v1.0/something/1?apiKey=1234abcdefghijklmnop';
    const getValuesRequest = new XMLHttpRequest();
    getValuesRequest.responseType = 'json';
    getValuesRequest.open('GET', getOptionValuesUrl);
    getValuesRequest.send();
    getValuesRequest.onreadystatechange = function () {
        const response = getValuesRequest.response;
        if (response) {
            if (getValuesRequest.status == 200) {
                console.log('Success');
                if(validateIds(response)){
                    console.log('ID is Valid');
                    idStatus = true;
                }
                else {
                    console.log('ID is NOT Valid');
                    idStatus = false;
                }
           }
      }
    console.log(idStatus);
    return idStatus;
}
function validateIds(obj) {
    const data = obj['data'];
    console.log(data);
    let validId = '';
    for (let i = 0; i < data.length; i++) {
        if (data[i].id == 1) {
            validId = true;
        }
        else {
            validId = false;
        }
    }
    console.log(validId);
    return validId;
}

有效 ID 以应有的方式运行,getValues 控制台记录相应的响应,当它是 true 或 false 时,但 idStatus 始终返回 null。

【问题讨论】:

  • 您的代码仅更新“就绪”状态更改处理程序内部idStatus 值。这将在状态更改时运行,并且将在 getValues() 函数已经返回之后运行。

标签: javascript json get xmlhttprequest


【解决方案1】:

在这里,我为您的代码制作了一个更简单的版本。我使用 axios 而不是 XMLHttpRequest,因为它更易于使用。

const axios = require("axios");

async function getValues(link) {
  const response = await axios.get(link);
  if (!response.statusCode == 200) return false;
  if (response.data.some(elm => elm.id != 1)) return false;
  return true;
}
// if the status isn't 200, return false;
if (!response.statusCode == 200) return false;
// if one id isn't 1, return false;
if (response.data.some(elm => elm.id != 1)) return false;

如果您想了解更多有关 Array.some() 的详细信息,请点击此处的链接 Array.Some()

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 2020-12-07
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    相关资源
    最近更新 更多