如何分离嵌套的异步函数并以所需的顺序执行它们?

时间:2019-04-17 14:33:23

标签: javascript node.js module async-await puppeteer

我有一个异步函数,该函数将URL列表作为已解析的csv文件中的值。 在此函数中,我使用puppeteer启动页面并导航到每个URL。 我有两个功能-一个用于下载资源,另一个用于检查资源是否已下载。

  1. 我想先运行 scriptDownload(),执行完成后,运行 networkProfile()函数。

  2. 我还想知道这些功能是否可以隔离在单独的文件中,并应用模块导出和导入的功能。

我尚未初始化所附代码中的功能。

此外,稍后会在 networkProfile()中添加少量异步mongodb命令。

我曾尝试使用 .then ,但没有成功。始终 networkProfile() scriptDownload()

之前运行

还尝试将这些功能导出为单独的模块-但导致错误-页面-未识别的引用

const puppeteer = require('puppeteer');
var fse = require('fs-extra');
var Papa= require("papaparse");
const path = require('path');
var scr = require('./scripts');

async function scripts(x){
    const browser = await puppeteer.launch({ 
        headless: true,
        args: ['--enable-features=NetworkService'],
        ignoreHTTPSErrors:true
    });
    const page = await browser.newPage();
    const client = await page.target().createCDPSession();
    await client.send('Network.enable');
    await client.send('Network.clearBrowserCache');
    await client.send('Runtime.enable');
    await client.send('Debugger.enable');

    async function scriptDownload() {

        page.on('response', async resp => {
            const url = new URL(page.url()).host;
            const url1 = resp.request().url();
            var url2 = path.basename(url1);
            url2 = url2.replace(/\?/g, '&q');
            const isScript = resp.request().resourceType() === 'script';
            const isCSS = resp.request().resourceType() === 'stylesheet';
            const isXHR = resp.request().resourceType() === 'xhr';

            if (isScript) {
                let filePath = path.resolve(`./Responses/${url}/js/${url2}.js`);
                await fse.outputFile(filePath, await resp.text());
                console.log('Scripts Downloaded');
            }
            if (isCSS) {
                let filePath = path.resolve(`./Responses/${url}/css/${url2}.css`);
                await fse.outputFileSync(filePath, await resp.text());
                console.log('CSS Downloaded');
            }
            if (isXHR) {
                let filePath = path.resolve(`./Responses/${url}/xhr/${url2}.xhr`);
                await fse.outputFileSync(filePath, await resp.text());
                console.log('XHR Downloaded');
            }
        });
    }

    //network domian
    async function networkProfile() {
        client.on('Network.requestWillBeSent', parameters => {
            const request_url = parameters.request.url;
            var reqname = path.basename(request_url);
            var reqnamereg = reqname.replace(/\?/g, '&q');
            const urlloc = new URL(page.url()).host;
            try {
                    /**************************Check if file exists********************************************************** */
                    const jsFilePath = path.resolve(`./Responses/${urlloc}/js/${reqnamereg}.js`);
                    const jsPath = path.resolve(`./Responses/${urlloc}/js/${reqnamereg}`);
                    var locStorage = "null";

                    async function localjs(f) {
                        const existsjs = await fse.pathExists(f)
                        if (existsjs == true) {
                            locStorage = jsPath;
                            console.log(urlloc, reqnamereg, existsjs);
                        }
                        else {
                            locStorage = 'Js does not exist';
                            console.log(urlloc, reqnamereg, existsjs);
                        }
                    }

                    async function local(f) {
                        const exists = await fse.pathExists(f)
                        if (exists == true) {
                            locStorage = jsFilePath;
                            console.log(urlloc, reqname, exists);
                        }
                        else {
                            locStorage = 'File does not exist';
                            console.log(urlloc, reqname, exists);
                        }
                    }
                    if (reqname.endsWith('.js') == 'true') {
                        localjs(jsPath)
                    }
                    else {
                        local(jsFilePath)
                    }
            } catch (error) {
                console.log(error);
            }
        });
    }


    for (var j = 0; j < x.length; j++){
        try{
            await page.goto('https://www.' + x[j][1], { waitUntil: 'load' });
            const url = new URL(page.url()).host;
            let filePathhtml = path.resolve(`./Responses/${url}/html/${url}.html`);
            await fse.outputFileSync(filePathhtml, await page.content());
        }
        catch(error){
            if(error==='net::ERR_CONNECTION_TIMED_OUT'){
            }
        }
    }

    setTimeout(async () => {
        await page.close();
        await browser.close();
    }, 60000 * 2);
}

file = fse.createReadStream(__dirname + '/test.csv', 'utf8')
function parseData(file, callBack) {
    Papa.parse(file, {
        delimiter: "",  // auto-detect
        newline: "",    // auto-detect
        header: false,
        download: true,
        complete: function(results) {
            callBack(results.data);
        }
    });
}
parseData(file, scripts);

预期结果将是

已下载脚本

CSS已下载

...

...

...

url,reqname,true(对于脚本),否则为false

1 个答案:

答案 0 :(得分:0)

只需将它们放在不同的函数中,然后将参数传递给它们


        <div class="search-tab-content">
            <div class="search-bar">
                <input type="text" id="search-text" placeholder="Search Catalog" name="qu">
                <input type="image" alt="go" id="search-text-icon" title="Search" src="img.png">
            </div>
        </div>

但是我认为您做的不对,您尝试检查函数内的事件也应该称为