Reputation: 53
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.
Upvotes: 0
Views: 273
Reputation: 9447
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.
Upvotes: 1
Reputation: 3404
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.
Upvotes: 0