Node.js:你能使用stream内的asynchronous函数吗?

考虑以下:

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已经完成? 有没有什么办法从stream内使用asynchronous函数?

查看转换stream。 它们使您能够在块上运行asynchronous代码,然后在完成时调用callback函数。 这里是文档: 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)