【问题标题】:Iterate over CSV file and run await for each row?遍历 CSV 文件并为每一行运行等待?
【发布时间】:2020-01-30 07:45:39
【问题描述】:

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

我该怎么做?

我有:

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); 行抛出错误。

【问题讨论】:

  • 你需要让回调函数异步 -> .on('data', async (row) => {...
  • 谢谢,如果我改变我得到UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 542) 但也许这与我的getFile 功能不正确有关?
  • 使回调函数异步不会导致管道暂停,直到返回的承诺解决
  • 我应该应该做什么?好困惑:(
  • @Richard 请查看我发布的答案,让我们知道它是否有效。 :)

标签: javascript node.js promise async-await


【解决方案1】:

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

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');
    });

【讨论】:

    【解决方案2】:

    由于getFile 函数已经是一个promise,您可以使用promise 函数暂停和恢复管道,而无需使函数异步。

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

    【讨论】:

      猜你喜欢
      • 2020-05-15
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      • 2018-08-24
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      相关资源
      最近更新 更多