如何以一种干净的方式使cheerio的`$`在辅助函数中可访问?

时间:2018-11-05 08:25:12

标签: javascript function cheerio

我对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 :(得分:1)

由于未定义传递给getPage函数的 nextPage 变量而显示错误。它仅存在于process1函数的范围内。

深入了解Promises。有了它,您可以链接将要彼此运行的方法。在成功回调中返回一个新的Promise,链中的下一个方法将暂停,直到当前的Promise被解决为止。

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
  });