簡體   English   中英

使用node.js在流中進行異步調用的問題

[英]Problems with making async calls in streams using node.js

我在流中進行異步調用時遇到問題。 由於某些原因,如果我有三個流,並且中間流進行異步調用,則最終流永遠不會收到“ end”事件。 我可以通過一些簡單的流和超時來模擬行為。

var options = {}
var streamOne = function(){
  return through(function write(row){
    this.emit('data', row)       
  })
}

var streamTwo = function(){
  return through(function write(row){
    this.pause()
    var that = this;

    setTimeout(function(){
      that.emit('data', row)
      that.resume()
    }, 1000)
  })
}

options.streams = [new streamOne(), new streamTwo()]

然后,我將其傳遞給event-stream

var streams = []
//Pass stream one and stream two to es.pipe
streams.push(es.pipe.apply(this, options.streams))

//Then add the final stream 
var endStream = es.pipe(
  new streamThree()
)
streams.push(endStream)

//And send it through the pipeline
es.pipeline.apply(this, streams)

因此,這在當前情況下不起作用。

有兩點令人困惑:如果刪除streamOne,它會起作用! 如果streamTwo沒有進行異步調用,則它可以工作。 這使我認為問題出在兩個流交互的方式上。 但是,如果我在整個代碼中使用console.log ,看起來一切正常,streamThree會寫入數據,但永遠不會注冊“ end”事件。 *注意:streamThree未使用直通,而是使用本機Streams模塊。

關於為什么會這樣的想法?

在運行了一些測試用例之后,看起來好像管道或直通沒有正確處理I / O。 我不完全確定為什么會這樣,但是我認為是由於爭用情況而導致的流暫停和恢復。 我做了一些事情來清理代碼:

1)簡化管道。 我沒有直接在管道中嵌套es.pipe ,而是直接將流放入其中。 這有助於更好地管理流之間的數據流。

2)我沒有使用常規流發送數據,而是使用this.queue對數據進行this.queue ,讓模塊處理潛在的背壓。

3)我使用事件流方法es.map來處理異步調用的流程。 我認為這是一個更好的解決方案,因為它可以更干凈地處理流的暫停和恢復,並且仍然返回直通流。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM