Dmitry  Sokolov
Dmitry Sokolov

Reputation: 1383

Fetch API in sync functions and for loop

var lineArr = [];
    var MAX_LENGTH = 10;
    var duration = 500;
    var chart = realTimeLineChart();

function getData() {
  fetch('./getRealTimeData').then((response) => response.json()
.then((data) => {
  return data;
}));
}

function seedData() {
  var now = new Date();
  for (var i = 0; i < MAX_LENGTH; ++i) {
    let data = getData();
    lineArr.push({
      time: new Date(now.getTime() - ((MAX_LENGTH - i) * duration)),
      x: data.x,
      y: data.y,
      z: data.z
    });
  }
}

function updateData() {
  var now = new Date();
  let data = getData();

  var lineData = {
    time: now,
    x: data.x,
    y: data.y,
    z: data.z
  };
  lineArr.push(lineData);

  if (lineArr.length > 30) {
    lineArr.shift();
  }
  d3.select("#chart").datum(lineArr).call(chart);
}

function resize() {
  if (d3.select("#chart svg").empty()) {
    return;
  }
  chart.width(+d3.select("#chart").style("width").replace(/(px)/g, ""));
  d3.select("#chart").call(chart);
}

document.addEventListener("DOMContentLoaded", function() {
  seedData();
  window.setInterval(updateData, 250);
  d3.select("#chart").datum(lineArr).call(chart);
  d3.select(window).on('resize', resize);
});

result:

rt_st.js:19 Uncaught TypeError: Cannot read property 'x' of undefined
    at seedData (rt_st.js:19)
    at HTMLDocument.<anonymous> (rt_st.js:53)

Because fetch is async it can have many problems to use in sync context, an don't understand how I can make this getData() function waiting while a request to the server is executed? Or what can I use instead fetch? Or I should use something else than fetch?

Upvotes: 2

Views: 2079

Answers (1)

0xnoob
0xnoob

Reputation: 1037

async function - JavaScript | MDN

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.


Add the async keyword to all functions that use getData() and use the await keyword when you call getData():

async function seedData() {
  // ...
  let data = await getData();
  // ...

function updateData() {
  var now = new Date();
  let data = await getData();
  // ...

Upvotes: 4

Related Questions