javascript - nodejs 中http模块的async 用法
阿神
阿神 2017-04-17 16:35:58
[Node.js讨论组]

写了一个简单的基于chreeio的数据爬取代码,node http的模块获取html 然后用chreeio爬取。
想使用最新的async await 来异步操作.代码如下:

let request = require('request');
let cheerio = require('cheerio');
let fs = require('fs');
let http = require('http');
let https = require('https');

let newCollection = [];
let newCollection_item = {
    title: '',
    href: ''
};
const hrefPrefix = 'xxxxxxxxx'

class Crawler {
    static test() {
            // await getList();
            //想在这里直接获取newCollection
            console.log(this.getList());
        }
        //这里是一个异步获取list
    static async getList() {
        return new Promise((resolve, reject) => {
            http.get("http://xxxx/xxxxxx.com", (res) => {
                res.setEncoding('utf-8');
                let html = "";
                res.on('data', (chunk) => {
                    html += chunk;
                });
                res.on('end', () => {
                    let $ = cheerio.load(html);
                    //爬取数据
                    $('#ajaxtable tbody tr').each(function(index, item) {
                        if (index > 4) {
                            let title = $(this).children().eq(1).find('h3').find('a').text();
                            let href = `${hrefPrefix}` + $(this).children().eq(1).find('h3').find('a').attr('href');
                            newCollection_item = { title, href };
                            newCollection.push(newCollection_item);
                        }
                    }, this);
                    resolve(res);
                    // console.log("=============================================list=================================\n", newCollection)
                })
            })
        })
        return newCollection;
    }
}
Crawler.test();

不知道哪里写错了,目的就是想在test()里面能直接拿到getList返回的newCollection;

阿神
阿神

闭关修行中......

全部回复(1)
怪我咯

static async test()

async函数里才能用await

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号