Как сделать `` `` cheerio доступным во вспомогательных функциях чистым способом? - PullRequest
0 голосов
/ 05 ноября 2018

Я довольно новичок в JavaScript и пытаюсь реорганизовать это

const rp = require('request-promise');
const cheerio = require('cheerio'); // Basically jQuery for node.js

// shared function
function getPage(url) {
    const options = {
        uri: url,
        transform: function(body) {
          return cheerio.load(body);
        }
    };
    return rp(options);
}

getPage('https://friendspage.org').then($ => {

    // Processing 1
    const nxtPage = $("a[data-url$='nxtPageId']").attr('data');


    return getPage(nxtPage).then($ => {

        // Processing 2

    });
}).catch(err => {
    console.log(err);
    // error handling here
});

примерно так:

const rp = require('request-promise');
const cheerio = require('cheerio'); // Basically jQuery for node.js

// shared function
function getPage(url) {
    const options = {
        uri: url,
        transform: function(body) {
          return cheerio.load(body);
        }
    };
    return rp(options);
}

function process1(args) {
    // Processing 1
    return $("a[data-url$='nxtPageId']").attr('data');

}

function process2(args) {
    // Processing 2
}

getPage('https://friendspage.org').then($ => {

    const nxtPage = process1(args);        

    return getPage(nxtPage).then($ => {

        process2(args);

    });
}).catch(err => {
    console.log(err);
    // error handling here
});

но при этом выдает ошибку $ is not defined. Передав $ с args, я получаю ошибку от cheerio (или, по крайней мере, я думаю, что это от cheerio):

{ RequestError: Error: options.uri is a required argument
    at new RequestError (C:\Users\Skillzore\git\projects\gadl\node_modules\request-promise-core\lib\errors.js:14:15)
    at Request.plumbing.callback (C:\Users\Skillzore\git\projects\gadl\node_modules\request-promise-core\lib\plumbing.js:87:29)
    at Request.RP$callback [as _callback] (C:\Users\Skillzore\git\projects\gadl\node_modules\request-promise-core\lib\plumbing.js:46:31)
    at self.callback (C:\Users\Skillzore\git\projects\gadl\node_modules\request\request.js:185:22)
    at Request.emit (events.js:182:13)
...

Он печатает большой объект с несколькими подобными ошибками. Итак, что я делаю не так? И есть ли более чистый способ сделать это, чем передать $ вокруг?

1 Ответ

0 голосов
/ 05 ноября 2018

Ошибка отображается, потому что переменная nextPage , переданная в функцию getPage, не определена. Он живет только в рамках функции process1.

Посмотрите глубже на Обещания . С его помощью вы можете связывать методы, которые будут запускаться после друг друга. Верните новое обещание в обратном вызове успеха, и следующий метод в цепочке остановится, пока текущее обещание не будет разрешено.

function process1($) {
  // Process stuff
  // What you return here will be passed to the next function in the promise chain below (in this case a string)
  return $("a[data-url$='nxtPageId']").attr('data');
}

function process2(nextPage) {
  // More processing
  // getPage will return a promise which eventually gets resolved with the cheerio object
  return getPage(nextPage);
}

function process3($) {
  // More processing?
}

getPage('https://friendspage.org')
  .then(process1)
  .then(process2)
  .then(process3)
  .catch(err => {
      console.log(err);
      // error handling here
  });
...