【问题标题】:How can I pass json data returned from a Fetch function to another function? [duplicate]如何将 Fetch 函数返回的 json 数据传递给另一个函数? [复制]
【发布时间】:2019-11-30 12:39:00
【问题描述】:

我希望使用 Fetch() 或 Jquery GetJson() 每 5 秒独立获取一些 json 数据(json 文件)。

我希望另一个函数使用该数据并在循环中显示一个名称数组,一次选择 8 个(大约 100 个名称)。 (待实施)

我该如何等待数据?我知道我需要等待数据异步返回。

var data = null;
var dataPath = "../data/GolfData.json";

$(document).ready(function () {
  console.log('working...');
  DisplayData(data);
});


/* Fetch Data
------------------------------------------  */
function FetchData() {
  fetch(dataPath)
    .then(function (response) {
      return response.json();
    })
    .then(function (json) {
      data = json;
      console.log(data)
      return data;
    })
    .catch(function (error) {
      setInterval(FetchData, 5000);
      console.log(error);
    })
}
FetchData();
setInterval(FetchData, 5000);

function DisplayData(data) {
 console.log('data ', data);
}

控制台:数据为空

【问题讨论】:

  • 将您的DisplayData 函数放入.thenfetch(dataPath).then(...).then(...).then(DisplayData)
  • @ktilcu 但这将意味着每 5 秒也会调用一次 DisplayData(data)。正确的?我想避免这种情况。
  • 是的。所以你想每 5 秒获取一次数据,将其存储在某个地方,然后在稍后的某个时间显示最新数据?
  • @ktilcu 是的。我该怎么做呢?
  • @nbokmans,不确定我是否会将其归类为重复,另一个问题更普遍地是关于异步请求,而不是关于如何定期执行它们等......

标签: javascript html fetch-api


【解决方案1】:

这个方向的东西可能会有所帮助。下面的示例只是每 5 秒执行一次对 URL 的请求,永远 =)...当数据返回时,您将做什么由您决定。如果您不希望 DisplayData() 函数每 5 秒运行一次,则必须实现某种条件逻辑,让代码决定 DisplayData() 是否应该运行......

// Not declared `async` because it returns a promise already
function wait(ms) {
  // Returns a promise that we can `await`
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      console.log(`Waiting for ${ms}ms`);
      // Resolve the promise with the timeout value,
      // not really important here with what it is resolved
      resolve(ms);
    }, ms);
  });
}


async function getData() {
  try {
    // GET some data from whereever
    let response = await fetch('https://randomuser.me/api/?inc=gender,name,nat&results=10');

    let data = await response.json();
    
    return data;
  } catch(err) {
    console.log(err);
    return null;
  }
}

// IIFE to use `await` at the top level
(async function() {
  // this is an infinite loop, for developing you might want
  // a way to stop it, can crash your browser if you mess
  // it up inside =)...
  while (true) {
    console.log('getting data...');
    let data = await getData();
    console.log(data);
    
    // here you do something with the new data...
    // e.g. call your `DisplayData(data)` function
    
    // then wait for 5 seconds
    await wait(5000);
  }
})();

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多