遍历CSV文件并等待每一行吗? [英] Iterate over CSV file and run await for each row?

查看:126
本文介绍了遍历CSV文件并等待每一行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历节点中的CSV文件,并为每一行调用一个异步函数并等待其完成.

I want to iterate over a CSV file in node, and for each row, call an asynchronous function and wait for it to complete.

我该怎么做?

我有:

const getFile = async function(url) {
    const response = await page.goto(url, { waitUntil: 'networkidle2' });
    await page.waitFor(3000);
    const ad = await page.waitForSelector('div.chart');
    await ad.screenshot({
        path: path
    });
};

fs.createReadStream(fname)
    .pipe(csv())
    .on('data', (row) => {
        let id = row.ad_id;
        let url = 'xxxx' + id;
        await getFile(path);
    }).on('end', () => {
        console.log('CSV file successfully processed');
    });

但是这给了我SyntaxError: await is only valid in async function,并在await getFile(path);行上抛出了错误.

But this gives me SyntaxError: await is only valid in async function, throwing the error on the await getFile(path); line.

推荐答案

您将收到SyntaxError,因为正如它所说,await仅在async函数中有效.您可以通过使回调async来解决此问题,但仅此一项,就不会导致管道停止发出进一步的data事件,直到异步函数完成为止.但是,您可能可以像这样手动进行操作:

You're getting a SyntaxError because, as it says, await is only valid in an async function. You can fix this by making your callback async, but that alone won't cause the pipe to stop emitting further data events until the async function finishes. You can probably, however, do this manually like so:

const csvPipe = fs.createReadStream(fname).pipe(csv());
csvPipe.on('data', async (row) => {
        csvPipe.pause();
        let id = row.ad_id;
        let url = 'xxxx' + id;
        await getFile(path);
        csvPipe.resume();
    }).on('end', () => {
        console.log('CSV file successfully processed');
    });

这篇关于遍历CSV文件并等待每一行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆