请考虑以下事项:
var asyncFunction = function(data, callback) {
doAsyncyThing(function(data){
// do some stuff
return callback(err)
})
}
fs.createReadStream('eupmc_lite_metadata_2016_04_15.json')
.pipe(JSONstream.parse())
.on('data', asyncFunction) // <- how to let asyncFunction complete before continuing
当asyncFunction完成时,流如何知道?有没有办法在流中使用异步函数?
答案 0 :(得分:14)
查看转换流。它们使您能够在块上运行异步代码,然后在完成后调用回调。以下是文档:https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback
举个简单的例子,您可以执行以下操作:
const Transform = require('stream').Transform
class WorkerThing extends Transform {
_transform(chunk, encoding, cb) {
asyncFunction(chunk, cb)
}
}
const workerThing = new WorkerThing()
fs.createReadStream('eupmc_lite_metadata_2016_04_15.json')
.pipe(JSONstream.parse())
.pipe(workerThing)