gpt4 book ai didi

javascript - 如何以干净的方式在辅助函数中访问cheerio的 `$`?

转载 作者:行者123 更新时间:2023-12-03 00:48:27 25 4
gpt4 key购买 nike

我对 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)
...

它打印了一个大对象,但有几个这样的错误。那么,我做错了什么?有没有比传递 $ 更简洁的方法?

最佳答案

显示错误是因为传递给 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
});

关于javascript - 如何以干净的方式在辅助函数中访问cheerio的 `$`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53150702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com