I have try reading through the module called as Sync
and implemented the same in Node.js
in my code. But the problem is the code doesn’t seem to be running in sync. The code I have written is
var http = require('http'); var Sync = require('sync'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); console.log('Started the server and calling testRunning'); Sync(function(){ testRunning.sync(null); }); //testRunning(); res.end('Hello World!'); }).listen(8085); function testRunning(){ for(i=0;i<10;i++){ console.log('Running i:'+i); setTimeout(function() { //console.log('Blah blah blah blah extra-blah'); console.log('Ran i:'+i); }, 3000); } }
The problem which I am trying to solve is given a for loop of data, I would like the data to query the database and check if row doesn’t exists and then insert the row and get the primary key of the inserted row and perform operation. But because of async
nature, all the for loop executes at the first check of data. Do I have any way in which I can make it synchronous
in any way. This is one of the way I found, which doesn’t seem to work.