I'm having a bit of trouble with a NodeJS program I have.
So the way my for loop is supposed to function is, it should iterate through the indices from my SQL Database and in each run of the for loop, it's supposed to make a call to another function which makes a GET request.
What it actually does though is it iterates through all of my indices and THEN makes every GET request all at once/very fast, which ends up getting me limited from making anymore API calls. I tried using setTimeout but that doesn't work since it just iterates to the next index and the values end up being undefined.
Also tried a callback but it didn't change anything. I tried looking into async but can't really get my head around what I'm supposed to be doing. Also just a note, nothing is actually being returned. In my other function I'm just updating my SQL DB. I just need the for loop to make an API call per run and only continue after it's complete.
function callGet() {
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "USERNAME",
password: "PASSWORD",
database: "sys"
});
con.query("SELECT nameAlone FROM testDB", function(err, result, fields) {
var i;
for(i = 0; i < result.length; i++){
var name = result[i].nameAlone;
var options = {
method: 'GET',
url: 'site.com',
qs: {
key: 'MYKEY',
page_size: 10,
intent: 0,
itemName: name
},
headers: {
'postman-token': postman-token,
'cache-control': 'no-cache'
}
};
getListing(options,result, i); //Only being called after the for loop iterates through all of result.length
}
});
}
An example of what's happening is this, let's say the for loop iterates from 0-2 and each run calls a function that prints out a name. Instead of
index:0, name:Chris, index:1, name:Tony, index:2, name:John
It'll print out:
index:0, index:1, index:2, name:Chris, name:Tony, name:John
Thanks in advance for any help.
Edit: I already attempted all of the answers that applied to my issue in the duplicate question suggested. Trying to mess around with one of the answers there but not too sure if it'll work.
Edit2: All the solutions there didn't work.
Edit3(solution): In case anyone wants a very simple solution,I found this package which was very easy to setup: https://github.com/nathan818fr/async-loop
All I had to do was create an array with my indices and setup the asyncLoop as following:
asyncLoop(indices, function (item, next)
{
var name = result[item].nameAlone;
var options = {
method: 'GET',
url: 'site.com',
qs: {
key: 'MYKEY',
page_size: 10,
intent: 0,
itemName: name
},
headers: {
'postman-token': postman-token,
'cache-control': 'no-cache'
}
};
getListing(options,result, item);
next();
}, function ()
{
console.log('Finished!');
});