我有两个文件: server.js和scrape.js,下面是当前的代码片段。
server.js:
const scrape = require("./scrape");
async function start() {
const response = await scrape.start();
console.log(response);
}
start();和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
};所以当我旋转server.js时,我返回未定义的console.log(response),当我真的想返回我一直推入的数组时,你能看到我哪里错了吗?
发布于 2017-11-17 08:58:25
您需要从async函数返回一些内容( return中的返回不会从main函数返回)。要么是承诺,要么是you await-ed。
此外,请确保声明go变量,以避免将其泄漏到全局空间。
const go = async () => {
const options = {
uri: "http://www.somewebsite.com/something",
transform: function(body) {
return cheerio.load(body);
}
};
return 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);
});
};由于您使用的是async函数,因此可能还需要利用await语法。
const go = async () => {
const options = {
uri: "http://www.somewebsite.com/something",
transform: function(body) {
return cheerio.load(body);
}
};
try {
const $ = await request(options);
$(".some-class-in-html").each(function(i, obj) {
const data = $(this)
.text()
.trim();
scrapeTitleArray.push(data);
});
return scrapeTitleArray;
}
catch (err) {
console.log(err);
}
};发布于 2017-11-17 08:58:36
我相信你的go函数没有返回任何值。
您正在调用request(options).then(...),但是go永远不会返回该承诺之后的内容。我建议您添加一条return语句:
go = async () => {
const options = {
uri: "http://www.somewebsite.com/something",
transform: function(body) {
return cheerio.load(body);
}
};
// The only difference is that it says "return" here:
return 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);
});
};https://stackoverflow.com/questions/47341603
复制相似问题