A
A
Alexander Zim2015-04-14 11:52:16
JavaScript
Alexander Zim, 2015-04-14 11:52:16

How to make a synchronous loop in Node.JS?

Hello. I'm learning to program a little.
I have a number of links and I want the script to download the contents of each in turn and write it to the database. On php it worked with a simple cycle, it doesn't work here. I did so. But it is interesting to learn from experienced developers how you would do it.

var adresses = []; // ten values
connection.connect(); // mysql connection

function get(address, callback) {
  http.get(address, function(res) {
    var getted;
    res.on('data', function(part) {
      getted += part.toString();
    }).on('end', function() {
      callback(getted);
    });
  });
}

function getPages(counter) {
  get(adresses[counter], function(res) {
    connection.query('INSERT INTO porn (id, link) VALUES ('+(counter+1)+', '+res+')', function(error, result) {
      if (counter < adresses.length) {
        getPages(counter+1); // continue
      } else {
        connection.end(); // mysql close
      }
    });
  });
}

getPages(0);

Below is the code that I wrote specifically for the example. Something about the same works in my script.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nukkumatti, 2015-04-14
@3um

At the heart of Node.js is event-driven and asynchronous (or reactive) programming with non-blocking I/O .
You're Doing Node.js Wrong! Avoid Synchronous Code
Now solutions and examples (not just about how to make a synchronous loop)
https://github.com/lukehoban/es6features#promises
venkateshcm.com/2014/04/Reactor-Pattern-Part-3-Pro ...
tiku.io/questions/2881748/nodejs-synchronous-for-e... (first answer)
https://github.com/laverdet/node-fibers
venkateshcm.com/2014/04/Reactor- Pattern-Part-4-Wri...
Abstraction for node fibers to study source codes
https://github.com/ybogdanov/node-sync
https://github.com/jtblin/syncho
https://github.com/lukehoban/es6features#generators
https://github.com/luciotato/waitfor -ES6
Threads and Fibers
Generators vs Fibers
ES6 generators or promises _ _ _ _ _ _ _ _
Enough reading for now?
Do not hesitate to contact me when information hunger strikes again
Avoid Synchronous Code <3

S
smanioso, 2015-04-14
@smanioso

https://github.com/caolan/async

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question