Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  179] [ 3]  / answers: 1 / hits: 52144  / 10 Years ago, fri, may 16, 2014, 12:00:00

I want to do a for each loop but have it run synchronously. Each iteration of the loop will do an http.get call and that will return json for it to insert the values into a database. The problem is that the for loop runs asynchronously and that causes all of the http.gets to all run at once and my database doesn't end up inserting all of the data.I am using async-foreach to try to do what I want it to do, but I don't have to use it if I can do it the right way.



mCardImport = require('m_cardImport.js');
var http = require('http');
app.get('/path/hi', function(req, res) {

mCardImport.getList(function(sets) {
forEach(sets, function(item, index, arr) {
theUrl = 'http://' + sets.set_code + '.json';
http.get(theUrl, function(res) {

var jsonData = '';
res.on('data', function(chunk) {
jsonData += chunk;
});

res.on('end', function() {
var theResponse = JSON.parse(jsonData);
mCardImport.importResponse(theResponse.list, theResponse.code, function(theSet) {
console.log(SET: + theSet);
});
});
});
});
});
});


and my model



exports.importResponse = function(cardList, setCode, callback) {

mysqlLib.getConnection(function(err, connection) {

forEach(cardList, function(item, index, arr) {

var theSql = INSERT INTO table (name, code, multid, collector_set_num) VALUES
+ (?, ?, ?, ?) ON DUPLICATE KEY UPDATE id=id;
connection.query(theSql, [item.name, setCode, item.multid, item.number], function(err, results) {
if (err) {
console.log(err);
};
});
});
});
callback(setCode);
};

More From » mysql

 Answers
7

I found out that I wasn't releasing my mysql connections after I was done with each call and this tied up the connections causing it to fail and appear to be an issue with synchronization.



After explicitly calling connection.release(); it caused my code to work 100% correctly even in an asynchronous fashion.



Thanks for those who posted to this question.


[#70978] Thursday, May 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamryn

Total Points: 645
Total Questions: 100
Total Answers: 118

Location: Tanzania
Member since Wed, Feb 24, 2021
3 Years ago
kamryn questions
Sun, Apr 10, 22, 00:00, 2 Years ago
Sun, Oct 3, 21, 00:00, 3 Years ago
Thu, May 28, 20, 00:00, 4 Years ago
Tue, May 12, 20, 00:00, 4 Years ago
;