I have two files; server.js and scrape.js, below are the code snippets as they currently stand.
server.js:
const scrape = require("./scrape");
async function start() {
const response = await scrape.start();
console.log(response);
}
start();
and scrape.js:
const cheerio = require("cheerio");
const request = require("request-promise");
go = async () => {
const options = {
uri: "http://www.somewebsite.com/something",
transform: function(body) {
return cheerio.load(body);
}
};
request(options)
.then($ => {
let scrapeTitleArray = [];
$(".some-class-in-html").each(function(i, obj) {
const data = $(this)
.text()
.trim();
scrapeTitleArray.push(data);
});
return scrapeTitleArray;
})
.catch(err => {
console.log(err);
});
};
module.exports = {
start: go
};
So when I spin up server.js, I return undefined to the console.log(response), when I actually want to return the array i've been pushing to, can you see where I'm going wrong?
.each()
uses a "callback". You need to wrap that in a promise and resolve it's result. Otherwise the code just skips straight to returning the empty array. You need toreturn
therequest
result of course, but if you don't respect the callback then you're still going to have problems. – Susumugo
is an implicitly global variable. Don't do that. – Lookerongo
as anasync
function but then nowhere useawait
? – Lookeron