This question is a follow-up from this thread - setTimeout inside a loop, stops script from working
I'm facing an issue with my script that fetches data from an API and stores it in a MongoDB collection. The problem seems to be related to the setTimeout()
function, as it prevents the script from running a second time.
For more information on the issue, you can check out this article - Watch Out When Using SetTimeout() in For Loop #JS
Problematic code area:
const callIt = () => {
fetch(`https://api.binance.com/api/v3/klines?symbol=${symbols[cnt]}&interval=30m&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]),
Timespan: 30,
}
});
console.log(btcusdtdata);
saveToDatebase(btcusdtdata);
cnt++;
if (cnt < symbols.length) setTimeout(callIt, 3000);
})
.catch((err) => {
console.log(err);
})
};
The script calls the API and processes through an array of symbols. How can I stop the setTimeout()
after it has gone through the entire array?
I have tried using clearTimeout(callIt)
but it does not seem to work for me.
EDIT1
Error: -
TypeError: data.map is not a function
FULLCODE
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 symbols = ["ZRXBTC",
"LENDBTC",
"AEBTC",
"AIONBTC",
"ALGOBTC",
"ARDRBTC",];
let cnt = 0;
const callIt = () => {
fetch(`https://api.binance.com/api/v3/klines?symbol=${symbols[cnt]}&interval=30m&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]),
Timespan: 30,
}
});
console.log(btcusdtdata);
saveToDatebase(btcusdtdata);
cnt++;
if (cnt < symbols.length) setTimeout(callIt, 3000);
})
.catch((err) => {
console.log(err);
})
};
const j = schedule.scheduleJob('*/1 * * * *', callIt)
const saveToDatebase = function(BTCdata) {
const url = 'mongodb+srv://username:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="36465745454159445276555a4345425344061b075d435844185b59585159525418585342">[email protected]</a>/<dbname>?retryWrites=true&w=majority';
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;
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, db) => {
if (err) throw err;
const dbo = db.db('CryptoCurrencies');
const myobj = { Name: symbols[cnt - 1], Array: BTCdata, Date: dateTime };
dbo.collection(`${symbols[cnt - 1]}`).insertOne(myobj, (error, res) => {
if (error) throw error;
console.log('1 document inserted');
db.close();
});
});
};