0

how to make the below code synchronous in node.js

var abc;
request(url,function (error, response, html) {  //where url is website url
      abc = html;
}
console.log(abc);
console.log("some text");

I want that the first console log the html, which gets html from the url. the variable abc should not be undefined. I have to execute the above code in for loop. If there was no for loop, I can handle the above code synchronously using the step module in node.js.

jasmin9891
  • 53
  • 1
  • 6
  • 1
    Салман is totally right, it seems you are new to async programming, it is pretty hard to get your head around the traditional way of synchronous programming. However, there are libraries to make the process a bit easier, async is a great one https://github.com/caolan/async but you still need to think async when you write code. – user658991 Jan 22 '14 at 09:02
  • possible duplicate of [How can I make this call to request in nodejs synchronous?](http://stackoverflow.com/questions/9884418/how-can-i-make-this-call-to-request-in-nodejs-synchronous) – anvarik Jan 22 '14 at 09:30
  • As an alternative, to see whether you like NodeJS in the first place, you could use a language that compiles to JavaScript. An example would be IcedCoffeeScript, a coffee-script language that supports await/defer. – Deathspike Jan 22 '14 at 09:42

2 Answers2

1

This is not what node.js is for, if you're using node.js then you should follow async programming pattern. Unless you have some strong reason not to.

These links might help you understanding concepts of asynchronous programming model:

http://lostechies.com/johnteague/2012/11/30/node-js-must-know-concepts-asynchrounous/ http://stevehanov.ca/blog/index.php?id=127

Firstly, you should place that console inside the callback if you want it to execute after the request.

Second, you should never place an async code inside a for loop, instead use recursive function like I have shown below.

function fn()  {
    request(url,function (error, response, html) {  //where url is website url
        console.log(html);

        // here
        console.log("some text");
        if (condition) {
            fn();
        } else {
            // done
            done();
        }
    });
}

function done() {
    console.log('abc');
}

Keeping it in for loop will create a mess with scope because the complete loop will get executed before even the first callback occurs.

Salman
  • 9,299
  • 6
  • 40
  • 73
  • ok i can use this function but what if i want to write code(say want to write console.log("abc") below this function call so that the console in recursive function writes before the console i have written after the recursive function call code: fn(); console.write("abc"); this console should log after the console in fn() function – jasmin9891 Jan 22 '14 at 09:14
  • Meaning! You want to write a `console.log` below (after) the function call, and want it to execute before `console.log(html);`? What exactly you want! Why you want to complicate your life by writing code in wrong sequence and expect it to be executed correctly? – Salman Jan 22 '14 at 09:16
  • if i call this recursive function fn(); & then if i write the console.log("abc") this abc will be logged before the console.log(html) which is in the recursive function. I dont want this way. – jasmin9891 Jan 22 '14 at 09:29
  • Well then your `console.log("abc")` should be in the `done()`, see the updated answer. I don't know what exactly your usecase is, so can't say whether you should use things like fibers or co as suggested in bduran's answer – Salman Jan 22 '14 at 09:33
0

Short answer: Is not supported.

But you can do it with fibers. Fibers is a library that is written in c++ to allow stuff that you can't get at node.js level.

To add some sugar to fibers (although you can do your own implementation) you can use node-sync:

  function asyncFunction(a, b, callback) {
      setTimeout(function(){
          callback(null, a + b);
      }, 1000)
  }


  var result = asyncFunction.sync(null, 2, 3);
  console.log(result); // 5 (after 1 sec)

But if you don't like the way of write in node.js I suggest you to use co or a library that implements promises. Using fibers (and force node.js to be synchronous) to embellish the code it's a bad, bad idea.

durum
  • 3,316
  • 1
  • 25
  • 30