首页 > 解决方案 > 循环内的 if 语句有效。但不是在我添加“循环”/“重复”获取之后

问题描述

我之前发布了一个类似的问题,但我不够简洁。所以,我来了!

我正在从网站获取一些数据,一组对象,然后循环通过它来修改它。我正在修改它仅仅是因为我需要在数组中的每个对象内添加新元素,以便稍后在它们上运行一些“if 语句”。

我发现我的循环和 if 语句在没有 fetch 函数的情况下可以正常工作。但是,当我添加它时,应该返回 true 的 if 语句则不然。

示例代码在底部。

如果我按原样运行它,这是在 fetch 之外工作的部分(在我获得对象的数据数组之后。我在没有 fetch 的情况下运行代码,一切都很好。)

if (time < new Date(new Date(Date.now()).toLocaleString('en-US', {timeZone: 'UTC'}))) {
  var time = new Date(new Date(Date.now()).toLocaleString('en-US', {timeZone: 'UTC'}))
  //changing time with current time in UTC if time is "smaller"
} else {
  //do nothing
}

for (let i = 0; i < data.length; i++) {
  data[i]['ontime'] = (new Date(new Date(data[i].starttime).toLocaleString('en-US', {timeZone: 'UTC'})))
  data[i]['estimatedtime'] = dateAdd(new Date(time), 'second', Math.round(data[i].distance.value / 50 * 60 * 60))
  for (let j = 0; j < data.rooms.length; j++) {
    /*push and save some elements*/
  }

  if (data[i].ontime > data[i].estimatedtime) {
    //do something
  } else { // repeat fetch if the condition is false
    console.log('unsuitable!')
    getData()
  }
}

我试图做两个循环。一个用于改变数据数组的对象,另一个用于 if 语句 +我为这两个单独的循环使用了 asynch/await 函数,以确保第二个循环(if 语句)仅在第一个循环完成后开始。它似乎不起作用。以前,我发布了错误与日期有关,它显示“无效日期”。我解决了这个问题,但我仍然有同样的问题。

var errorcheck = []
time = new Date('11/2/2019 14:25')

function getData() {
  fetch(fetch_url)
    .then((response) => {
      if (!response.ok) {
        errorcheck.push(response.status)
      } // if response is not ok, i store the error code.
      else if (response.ok) {
        response.json()
          .then(data => data = data)
          .then(() => {
            if (data.length > 0) { // checking if any "data array" has objects
              if (time < new Date(new Date(Date.now()).toLocaleString('en-US', { timeZone:'UTC'}))) {
                var time = new Date(new Date(Date.now()).toLocaleString('en-US', { timeZone:'UTC'}))
                //changing time with current time in UTC if time is "smaller"
              } else {
                //do nothing
              }

              for (let i = 0; i < data.length; i++) {
                data[i]['ontime'] = (new Date(new Date(data[i].starttime).toLocaleString('en-US', {timeZone: 'UTC'})))
                data[i]['estimatedtime'] = dateAdd(new Date(time), 'second', Math.round(data[i].distance.value / 50 * 60 * 60))

                for (let j = 0; j < data.rooms.length; j++) {
                  /*push and save some elements*/
                }

                if (data[i].ontime > data[i].estimatedtime) {
                  //do something
                } else { // repeat fetch if the condition is false
                  console.log('unsuitable!')
                  getData()
                }
              }
            } else {
              console.log('no object in data!')
              getData() //if data array had no objects inside, i repeat the fetch
            }
          })
      }
    })
}

更新:

我已经取出了下一个代码,它也适用于 fetch。

if (time < new Date(new Date(Date.now()).toLocaleString('en-US', { timeZone:'UTC'}))) {
                var time = new Date(new Date(Date.now()).toLocaleString('en-US', { timeZone:'UTC'}))
                //changing time with current time in UTC if time is "smaller"
              } else {
                //do nothing
              }

每次运行 fetch 时,我都需要运行此代码。否则,时间戳 ( estimatedtime) 将完全无关紧要。我也试着.then在第一和第二之后再做一秒。time没有更新。就像timeestimatedtime因此)我还有其他变量需要在每次运行或完成提取时进行修改。

标签: javascriptloopsdateif-statementfetch

解决方案


我不是 100% 确定您在此处所需的逻辑,我只是​​在文档中添加一个元素并附加一个事件并在需要更多数据时触发该事件。

我还创建myApp了保存值而不是多个全局变量。

var myApp = myApp || {
  errorcheck: []
};
// these could be in the object above like the errorcheck is
myApp.lastTimestamp = new Date();
myApp.fetch_url = "some/urlthing";
myApp.time = new Date.UTC();

var aNewDivElement = document.createElement("div", {
  id: "newDivElement"
});
var getMoreDataEvent = new Event('getMoreData');
aNewDivElement.addEventListener('getMoreData', function(e) {
  myApp.getData();
}, false);

document.body.appendChild(aNewDivElement);
var divHoldEvents = document.getElementById("newDivElement");

myApp.getData = function() {
  fetch(myApp.fetch_url)
    .then(function(response) {
      if (response.ok) {
        let data = response.json();
        // checking if any "data array" has objects
        if (data.length > 0) {
          myApp.myUtcDateTime = new Date.UTC();
          if (myApp.time < myApp.myUtcDateTime) {
            myApp.time = myApp.myUtcDateTime;
          }
          for (let i = 0; i < data.length; i++) {
            // seems odd to do these, do we mean the new array?
            data[i].ontime = myApp.myUtcDateTime;
            let est = dateAdd(new Date(myApp.time), 'second', Math.round(data[i].distance.value / 50 * 60 * 60));
            data[i].estimatedtime = est;
            for (let j = 0; j < data.rooms.length; j++) {
              /*push and save some elements*/
            }
            if (data[i].ontime > data[i].estimatedtime) {
              //do something
            } else { // repeat fetch if the condition is false
              console.log('unsuitable!');
              divHoldEvents.dispatchEvent(getMoreDataEvent);
            }
          }
        } else {
          console.log('no object in data!');
          //if data array had no objects inside, i repeat the fetch
          divHoldEvents.dispatchEvent(getMoreDataEvent);
        }
      } else {
        // if response not ok, store the error code.
        this.errorcheck.push(response.status);
      }
    });

};
// start things off 
divHoldEvents.dispatchEvent(getMoreDataEvent);


推荐阅读