【发布时间】:2021-11-17 17:46:08
【问题描述】:
我有一些 Javascript 代码,它的行为与我预期的不一样。谁能告诉我这里发生了什么?
这是一个简化版:
let recordsProcessed = 0
await parser(fileBuffer,
// Process row
async (row: Record<string, any>) => {
recordsProcessed += 1
try {
console.log('Processing record', recordsProcessed)
await processRow(row)
} catch (e) {
console.log('Failure at record', recordsProcessed)
}
}
)
async parser(fileBuffer: Buffer, rowCb: Function, ...) : Promise<number> {
...
return new Promise((resolve, reject) => {
parseFile(fileBuffer, options)
.on('error', (error:any) => reject(error))
.on('data', async row => await rowCb(row))
.on('end', (count: any) => resolve(count))
})
...
}
这里的 parser() 是一个异步函数,但它也调用了一些传递给它的回调(我这里只展示了一个,但有多个)。它为文件中的每一行调用 rowCb() 回调。
这是异步回调中的 try/catch 块,它的行为不符合我的预期。我正在使用一个包含三行的测试文件,这将导致对 processRow() 的每次调用都会引发异常。所以,我希望 console.logs 的输出是:
Processing record 1
Failure at record 1
Processing record 2
Failure at record 2
Processing record 3
Failure at record 3
但我却得到了这个:
Processing record 1
Processing record 2
Processing record 3
Failure at record 3
Failure at record 3
Failure at record 3
为什么会这样?既然我在等待processRow(),它不应该和try/catch块在同一个范围内,因此catch()应该在processRow()抛出异常后立即处理吗?
【问题讨论】:
标签: javascript asynchronous async-await asynccallback