【发布时间】: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