Wie kann ich das mit Versprechen umschreiben?

Ich baue einen Content Scraper für eine T-Shirt-Website.

Das Ziel ist es, eine Website nur über eine fest codierte URL zu betreten:http://shirts4mike.com

Ich finde dann alle Produktseiten für jedes T-Shirt und erstelle ein Objekt mit seinen Details. Fügen Sie es dann einem Array hinzu.

Wenn das Array mit den T-Shirts gefüllt ist, arbeite ich das Array durch und logge es in eine CSV-Datei ein.

Rechts jetzt habe ich einige Probleme mit dem Timing der Anfragen / Antworten und den Funktionsaufrufen.

Wie kann ich sicherstellen, dass ich die NEXT-Funktion zum richtigen Zeitpunkt aufrufe? Ich verstehe, dass es nicht funktioniert, weil es asynchroner Natur ist.

Wie kann ich anrufensecondScrape, lastScraper undconvertJson2Csv zur richtigen Zeit, damit die Variablen, mit denen sie arbeiten, nicht undefiniert sind?

Ich habe versucht, etwas wie @ zu verwendresponse.end() aber das funktioniert nicht.

Ich gehe davon aus, dass ich Versprechen einlösen MUSS, damit das richtig funktioniert? und leserlich sein?

Irgendwelche Ideen? Mein Code ist unten:

//Modules being used:
var cheerio = require('cheerio');
var request = require('request');
var moment = require('moment');

//hardcoded url
var url = 'http://shirts4mike.com/';

//url for tshirt pages
var urlSet = new Set();

var remainder;
var tshirtArray;


// Load front page of shirts4mike
request(url, function(error, response, html) {
    if(!error && response.statusCode == 200){
        var $ = cheerio.load(html);

    //iterate over links with 'shirt'
        $("a[href*=shirt]").each(function(){
            var a = $(this).attr('href');

            //create new link
            var scrapeLink = url + a;

            //for each new link, go in and find out if there is a submit button. 
            //If there, add it to the set
            request(scrapeLink, function(error,response, html){
                if(!error && response.statusCode == 200) {
                    var $ = cheerio.load(html);

                    //if page has a submit it must be a product page
                    if($('[type=submit]').length !== 0){

                        //add page to set
                        urlSet.add(scrapeLink);

                    } else if(remainder === undefined) {
                        //if not a product page, add it to remainder so it another scrape can be performed.
                        remainder = scrapeLink;                     
                    }
                }
            });
        });     
    }
    //call second scrape for remainder
    secondScrape();
});


function secondScrape() {
    request(remainder, function(error, response, html) {
        if(!error && response.statusCode == 200){
            var $ = cheerio.load(html);

            $("a[href*=shirt]").each(function(){
                var a = $(this).attr('href');

                //create new link
                var scrapeLink = url + a;

                request(scrapeLink, function(error,response, html){
                    if(!error && response.statusCode == 200){

                        var $ = cheerio.load(html);

                        //collect remaining product pages and add to set
                        if($('[type=submit]').length !== 0){
                            urlSet.add(scrapeLink);
                        }
                    }
                });
            });     
        }
    });
    console.log(urlSet);
    //call lastScraper so we can grab data from the set (product pages)
    lastScraper();
};



function lastScraper(){
    //scrape set, product pages
    for(var i = 0; i < urlSet.length; i++){
        var url = urlSet[i];

        request(url, function(error, response, html){
            if(!error && response.statusCode == 200){
                var $ = cheerio.load(html);

                //grab data and store as variables
                var price = $('.price').text();
                var img = $('.shirt-picture').find("img").attr("src");
                var title = $('body').find(".shirt-details > h1").text().slice(4);

                var tshirtObject = {};
                //add values into tshirt object

                tshirtObject.price = price;
                tshirtObject.img = img;
                tshirtObject.title = title;
                tshirtObject.url = url;
                tshirtObject.date = moment().format('MMMM Do YYYY, h:mm:ss a');

                //add the object into the array of tshirts
                tshirtArray.push(tshirtObject); 
            }
        });
    }
    //call function to iterate through tshirt objects in array in order to convert to JSON, then into CSV to be logged
    convertJson2Csv();
};

Antworten auf die Frage(8)

Ihre Antwort auf die Frage