Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

how to make execution synchronous?

var request = require('request'); var json2csv = require('json2csv'); var cheerio = require('cheerio'); var url='http://www.shirts4mike.com'; var href;

request(url,function (error, response, body) { if (!error && response.statusCode == 200) { $ = cheerio.load(body); } else { console.log("error"); }

var shirts = $(".products li a"); shirts.each(function(){ href = $(this).attr('href');
request(url+'/'+href, function (error, response, body) { if (!error && response.statusCode == 200) { // console.log(body); // Show the HTML for the Google homepage. $ = cheerio.load(body); console.log($('.price').text()); console.log($('img').attr('src')); var csvFields = ["Title", "Price", "ImageURL", "URL", "Time"]; var json = {}; json.Price = $('.price').text(); json.URL=url+'/'+href; var d = new Date(); json.Time = d.getTime(); console.log(json); //json.ImageURL =

} else { console.log(error); } });

});

});

2 Answers

Michael Liendo
Michael Liendo
15,326 Points

Just a heads up to try and format your code so it's easier to read.

To answer your questions though, the ugly (wrong way) would be to nest your requests inside of the callback. A better solution is to use a library like async to let you control the flow a lot better and easier. Here's a direct link to the docs and the my suggested method to help you figure out the problem.

http://caolan.github.io/async/docs.html#eachOfSeries

thnx