router.get ("/ spider", async (ctx, next) = > {
var titles = []
await request ({
url:"http://caipiao.163.com/award/cqssc/",
gzip: true,
method:"GET"
}, function (e _ r _ b) {
// console.log(b)
if(!e){
var $ = cheerio.load(b);
$(".award-winNum").each(function (idx, element) {
var $element = $(element);
// console.log($element.text())
titles.push({
title: $element.text()
})
})
console.log(titles)
}
})
ctx.body = titles;
})
await is not waiting. May I ask how to solve the problem?
later Baidu solved the problem:
router.get ("/ spider", async (ctx, next) = > {
var that = ctx;
let postData = await spider (ctx)
ctx.body = postData;
})
function spider ()
{
return new Promise ((resovle, reject) = > {
try{
var titles = [ ]
request({
url:"http://caipiao.163.com/award/cqssc/",
gzip: true,
method:"GET"
},function(e,r,b){
// console.log(b)
if(!e){
var $ = cheerio.load(b);
$(".award-winNum").each(function (idx, element) {
var $element = $(element);
// console.log($element.text())
titles.push({
title: $element.text()
})
})
resovle(titles);
}
})
} catch (err) {
reject(err);
}
});