代码之家  ›  专栏  ›  技术社区  ›  Fergie

节点。js:你能在流中使用异步函数吗?

  •  27
  • Fergie  · 技术社区  · 9 年前

    考虑以下内容:

    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何时完成?有什么方法可以在流中使用异步函数吗?

    1 回复  |  直到 9 年前
        1
  •  24
  •   t7tran    3 年前

    签出转换流。它们使您能够在块上运行异步代码,然后在完成后调用回调。以下是文档: https://nodejs.org/api/stream.html#transform_transformchunk-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)