为了账号安全,请及时绑定邮箱和手机立即绑定

等待获取完成直到返回数据

等待获取完成直到返回数据

扬帆大鱼 2022-12-18 19:01:04
我想在提取完成时获取返回的数据,因为在完全提取后正确的时间戳将在那里,但是该函数将返回带有空时间戳而不是所有数据的最新时间戳的链接。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);
查看完整描述

1 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

Promise您必须在此处通过使用async/来使用 JavaScript ,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()解决它。


以下是评论中提供的一些资源:async / await Stackoverflow Post MDN Docs


查看完整回答
反对 回复 2022-12-18
  • 1 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号