我如何将这些功能与承诺一起链接起来?

这是一个从t恤网站中删除数据然后将产品信息写入CSV文件的程序。

有3个刮擦功能和1个写入功能。

现在,我有一个绝对的噩梦试图让我的头在如何实现承诺这里没有任何第三方库或包。 这可能与只有ES6的本地功能?

由于请求的异步性质,我需要每个函数及其请求在下一个请求被调用之前完成。 这是因为我可以在下一个函数中使用urlSet等变量。

我怎样才能做到这一点,而不重写我的整个代码?

我应该提到,这些功能中的每一个都是基于个人的,它们都经过了多次测试。

每项功能都成为个人承诺吗?

代码如下,谢谢:

//TASK: Create a command line application that goes to an ecommerce site to get the latest prices.
    //Save the scraped data in a spreadsheet (CSV format).

'use strict';

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

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

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

var remainder;
var tshirtArray = [];


// First scrape loads front page of shirts4mike and finds the first product pages/menus
function firstScrape(){
    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;                         
                        }
                    }
                });
            });     
        }
    });
}


//Scrape next level of menus to find remaning product pages to add to urlSet
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);
                        }
                    }
                });
            });     
        }
    });
}


//call lastScraper so we can grab data from the set (product pages)
function lastScraper(){
    //scrape set, product pages
    for(var item of urlSet){
        var url = item;

        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 imgURL = $('.shirt-picture').find('img').attr('src');
                var title = $('body').find('.shirt-details > h1').text().slice(4);

                var tshirtObject = {};
                //add values into tshirt object
                tshirtObject.Title = title;
                tshirtObject.Price = price;
                tshirtObject.ImageURL = imgURL;
                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);
            }
        });
    }
}


//Convert array of tshirt objects and write to CSV file
function convertJson2Csv(){
    //The scraper should generate a folder called `data` if it doesn’t exist.
    var dir ='./data';
    if(!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }

    var fields = ['Title', 'Price', 'ImageURL', 'URL', 'Date'];

    //convert tshirt data into CSV and pass in fields
    var csv = json2csv({ data: tshirtArray, fields: fields });

    //Name of file will be the date
    var fileDate = moment().format('MM-DD-YY');
    var fileName = dir + '/' + fileDate + '.csv';

    //Write file
    fs.writeFile(fileName, csv, {overwrite: true}, function(err) {
        console.log('file saved');
        if (err) throw err;
    });
}

如果你想用promise来链接这些函数,那么他们必须返回promise

如果你想链接他们与async模块,那么他们必须把回调作为参数。

现在他们既没有回复承诺 (或其他), 也没有将回调 (或其他)作为参数。 如果函数没有回调并且没有返回任何东西,那么你只需要调用它就可以了。 您将不会收到任何结果的通知。

回调

如果你有3个函数需要回调函数:

function fun1(cb) {
  setTimeout(() => {
    cb(null, "fun1");
  }, 1000);
}
function fun2(cb) {
  setTimeout(() => {
    cb(null, "fun2");
  }, 3000);
}
function fun3(cb) {
  setTimeout(() => {
    cb(null, "fun3");
  }, 100);
}

然后你可以知道他们何时完成:

fun3((err, value) => {
  console.log('fun3 finished:', value);
});

在开始另一个之前,你可以轻松地等待一个:

fun1((err1, val1) => {
  fun2((err2, val2) => {
    console.log("fun1 + fun2:", val1, val2);
  });
});

承诺

如果你的函数返回promise:

function fun1() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res("fun1");
    }, 1000);
  });
}
function fun2() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res("fun2");
    }, 3000);
  });
}
function fun3() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res("fun3");
    }, 100);
  });
}

那么你也可以知道他们什么时候完成:

fun3().then(value => {
  console.log('fun3 finished:', value);
});

您也可以轻松嵌套电话:

fun1().then(val1 => {
  fun2().then(val2 => {
    console.log("fun1 + fun2:", val1, val2);
  });
});

要么:

fun1()
.then(val1 => fun2())
.then(val2 => fun3())
.then(val3 => console.log('All 3 finished in series'));

等等

为了能够更好地使用这两种风格,请参阅以下文档:

  • http://caolan.github.io/async/
  • http://bluebirdjs.com/docs/getting-started.html
  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
  • 链接地址: http://www.djcxy.com/p/55361.html

    上一篇: How can I chain these functions together with promises?

    下一篇: How can i return status inside the promise?