Javascript 迭代CSV文件并为每行运行wait?
我想在节点中迭代一个CSV文件,并为每一行调用一个异步函数,等待它完成 我该怎么做 我有:Javascript 迭代CSV文件并为每行运行wait?,javascript,node.js,promise,async-await,Javascript,Node.js,Promise,Async Await,我想在节点中迭代一个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'); aw
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仅在异步函数中有效,将错误抛出await-getFile(路径)代码>行 您得到了一个SyntaxError,因为正如它所说,await
仅在async
函数中有效。您可以通过使回调async
来解决此问题,但仅此一点不会导致管道停止发送进一步的数据
事件,直到async函数完成。但是,您可能可以这样手动执行此操作:
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');
});
由于getFile
函数已经是一个promise,因此可以使用promise函数暂停和恢复管道,而无需使函数异步
const csvPipe=fs.createReadStream(fname).pipe(csv());
csvPipe.on('数据',(行)=>{
csvPipe.pause();
设id=row.ad_id;
让url='xxxx'+id;
getFile(path).finally(()=>csvPipe.resume());
}).on('end',()=>{
console.log('CSV文件已成功处理');
});
您需要使回调函数异步->.on('data',async(row)=>{…
谢谢,如果我更改,我将获得未处理的PromisejectionWarning:未处理的承诺拒绝。此错误源于在没有catch块的异步函数中抛出,或者拒绝未使用.catch()处理的承诺。(拒绝id:542)
但也许这与我的getFile
函数不正确有关?使回调函数异步不会导致管道暂停,直到返回的承诺解决为止。我应该做什么?如此困惑:(@Richard请查看我发布的答案,并让我们知道它是否有效。)