-4

I want to get the returned data whenever fetching is done, because the correct timestamp will be there after fully fetching however the function will return the link with an empty timestamp instead of the latest timestamp of all the data.

async function pushData(url) {
  let settings = { method: "Get" };
  let timestamp = "";
  let i = 0;

  fetch(url, settings)
      .then(res => res.json())
      .then((json) => {
        json.forEach(function (object) {
          console.log(object);
          i++;
        });
        timestamp = json[i-1].timestamp;
      });

  return await 'https://www.bitmex.com/api/v1/trade?count=1000&symbol=XBTUSD&startTime=' + timestamp;
}

var test = pushData('https://www.bitmex.com/api/v1/trade?count=1000&symbol=XBTUSD');
console.log(test);
Kevin Koopman
  • 51
  • 1
  • 7

1 Answers1

1

You must utilise JavaScript Promise here by using async / await as I have done so in the code below for you:

async function pushData(url) {
  let settings = { method: "GET" };
  let timestamp = "";
  let i = 0;

  let res = await fech(url, settings)
  res = await res.json();

  res.forEach(function (object) {
    console.log(object);
    i++;
  });
  timestamp = res[i - 1].timestamp;

  return {
    res: res,
    timestamp: timestamp
  };
};

(async() => {
var test = await pushData('https://www.bitmex.com/api/v1/trade?count=1000&symbol=XBTUSD');
console.log(test);
console.log("Timestamp: " + test.timestamp)
console.log("Fetch Result: " + test.res)
})();

Since it this function is async, it returns a Promise which must be resolved as well. You didn't resolve it - You never used await or .then() to resolve it.

Here are some resources which were provided in the comments: async / await Stackoverflow Post MDN Docs

Static
  • 776
  • 4
  • 14
  • var test = await pushData is not possiblyed e, it is not in a function. Still the timestamp + fetch result is displayed first, then the data of variable test. – Kevin Koopman Aug 03 '20 at 19:06
  • I answered this question assuming that it is; I will amend the answer to function globally right now. – Static Aug 03 '20 at 19:07
  • I've just edited the question to resolve the issue which your comment highlighted. – Static Aug 03 '20 at 19:09