【问题标题】:Wait for fetching to be done untill returning data [closed]等待获取完成,直到返回数据[关闭]
【发布时间】:2020-11-23 20:41:21
【问题描述】:

我想在提取完成时获取返回的数据,因为在完全提取后会出现正确的时间戳,但是该函数将返回带有空时间戳的链接,而不是所有数据的最新时间戳。

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);

【问题讨论】:

  • 你为什么不等待获取,而不是一个字符串
  • 尽量不要混用await.then
  • 你的意思是把 await 放在 fetch 前面?这行不通。
  • 用法:const response = await fetch(URL);,参见thisstackoverflow 帖子
  • 这能回答你的问题吗? async / await fetch in node-js

标签: javascript node.js


【解决方案1】:

您必须在此处使用 JavaScript Promise,使用 async / await,正如我在下面的代码中为您所做的那样:

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)
})();

因为这个函数是async,所以它返回一个Promise,它也必须被解析。您没有解决它 - 您从未使用 await.then() 来解决它。

以下是 cmets 中提供的一些资源:async / await Stackoverflow PostMDN Docs

【讨论】:

  • var test = await pushData 不可能是 e,它不在函数中。还是先显示时间戳+获取结果,再显示变量test的数据。
  • 我回答了这个问题,假设它是;我现在将修改答案以在全球范围内发挥作用。
  • 我刚刚编辑了问题以解决您的评论突出显示的问题。
猜你喜欢
  • 2012-06-02
  • 2020-04-01
  • 1970-01-01
  • 2019-05-11
  • 2016-03-21
  • 2016-04-13
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多