循环遍历javascript数组以延迟调用API

时间:2020-06-15 10:16:28

标签: javascript

我有一个调用Binance API的脚本。我收到诸如BTCUSDT之类的特定符号的响应。 API不允许在API端点中调用多个符号。 该字符串-var j = schedule.scheduleJob('0 * * * *', function()是一个node-schedule package,它将每小时在00分钟(15:00/16:00/17:00 ...)调用脚本。

完整代码

var requestPromise = require('request-promise');
 const { MongoClient } = require('mongodb');
 const schedule = require('node-schedule');
 var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
 const fetch = require("node-fetch");

 var today = new Date();
 var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
 var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
 var dateTime = date + ' ' + time;

 var symbols = ["BTCUSDT", "ETHUSDT", "ATOMBTC"];
 let cnt = 0;

 const callIt = () => {
     fetch(`https://api.binance.com/api/v3/klines?symbol=${symbols[cnt]}&interval=1h&limit=1`)
         .then(res => res.json())
         .then(data => {
             const btcusdtdata = data.map(d => {
                 return {
                     Open: parseFloat(d[1]),
                     High: parseFloat(d[2]),
                     Low: parseFloat(d[3]),
                     Close: parseFloat(d[4]),
                     Volume: parseFloat(d[5])
                 }
             });
             console.log(btcusdtdata);
             cnt++;
             if (cnt < symbols.length) setTimeout(callIt, 3000)
         })
         .catch((err) => {
             console.log(err);
         })

 };
 const j = schedule.scheduleJob('0 * * * *', callIt)

问题:此脚本一个接一个地调用数组内的属性,这对我来说是完美的。我的问题是节点计划(0 * * * *)不起作用。 我运行了脚本,它立即向我发送了数据。但是我不会只每小时接收一次数据,而只是在它要求数组中的属性之后才接收。如何在主函数内插入节点计划函数-const j = schedule.scheduleJob('0 * * * *', callIt)。 一切运行正常,只是脚本假设我启动时不会立即接收数据。

2 个答案:

答案 0 :(得分:2)

不要间隔执行Ajax。而是在回调中使用setTimeout

类似这样-注意,我在catch()中添加了一个拒绝项,以查看滥用API时的错误:

由于CORS问题,此处的代码无法正常运行

注意:${symbols[cnt]}是诀窍

const symbols = ["BTCUSDT", "ETHUSDT", "ATOMBTC"];
let cnt = 0;


const callIt = () => {
  fetch(`https://api.binance.com/api/v3/klines?symbol=${symbols[cnt]}&interval=1h&limit=1`)
    .then(res => res.json())
    .then(data => {
      const btcusdtdata = data.map(d => {
        return {
          Open: parseFloat(d[1]),
          High: parseFloat(d[2]),
          Low: parseFloat(d[3]),
          Close: parseFloat(d[4]),
          Volume: parseFloat(d[5])
        }
      })
      console.log(btcusdtdata);
      cnt++;
      if (cnt < symbols.length) setTimeout(callIt, 3000)
    })
    .catch((err) => {
      console.log(err);
    })
};

// callIt(); // only to test without scheduler
const j = schedule.scheduleJob('* * * * * *', callIt); // assuming this will call it first time

我想破坏但失败了。更加优雅

// https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=1

const data = [
  [1592215200000, "9147.70000000", "9150.00000000", "9107.00000000", "9114.93000000", "1335.61921100", 1592218799999, "12190574.36418155", 16160, "624.21625600", "5697793.49077209", "0"]
]
const d = data[0].slice(1,6);
const btcusdtdata = {};
["Open", "High", "Low", "Close", "Volume"].forEach((name,i) => btcusdtdata[name]=+d[i]);
console.log(btcusdtdata)

答案 1 :(得分:0)

如果您要执行介于两者之间固定时间的任务,则如下所示的wait函数将派上用场:

const symbols = ["BTCUSDT", "ETHUSDT", "ATOMBTC"];

function wait(ms) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, ms);
  });
}

const j = schedule.scheduleJob("* * * * * *", function () {
  ["BTCUSDT", "ETHUSDT", "ATOMBTC"].forEach((symbol, index) => {
    wait(2000 * index)
      .then(() =>
        fetch(
          `https://api.binance.com/api/v3/klines?symbol=${BTCUSDT}&interval=1h&limit=1`
        )
      )
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      })
      .catch(e => // do something with the error);
  });
});

如果您要一个接一个地执行异步任务,可以使用async/await关键字来编写更简洁的代码:

const symbols = ["BTCUSDT", "ETHUSDT", "ATOMBTC"];

const j = schedule.scheduleJob("* * * * * *", async function () {
  for (let i = 0; i < symbols.length; i++) {
    try {
      const symbol = symbols[i];
      const res = await fetch(
        `https://api.binance.com/api/v3/klines?symbol=${BTCUSDT}&interval=1h&limit=1`
      );
      const data = await res.json();
      conosle.log(data);
    } catch (e) { // do something with the error }
  }
});