flatMapConcat与嵌套流

时间:2015-01-08 19:00:24

标签: javascript node.js bacon.js

我问过“如何将流映射到延迟的promise流”,并发限制为1:map a stream to lazy promise stream。答案是flatMapConcat

现在我有两个嵌套流,需要并发限制为1,flatMapConcat不再有效。

var getPromise = function(value) {
  console.log('resolving ' + value);
  return new RSVP.Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve(value);
      }, 1000);
  });
};


var stream = Bacon.fromArray([1,2,3]).flatMapConcat(function(value) {
  return Bacon.fromPromise(getPromise(value));
});

//stream.log();
// nice sequential
// resolving 1
// 1
// resolving 2
// 2
// resolving 3
// 3

var secondStream = stream.flatMapConcat(function(promised) {
  return Bacon.fromPromise(getPromise('second' + promised));
});


secondStream.log();
// mixed up stream and secondStream, not sequential anymore
// resolving 1
// resolving second1
// resolving 2
// second1
// resolving second2
// resolving 3
// second2
// resolving second3
// second3

// Required output:
// resolving 1
// resolving second1
// second1
// resolving 2
// resolving second2
// second2
// resolving 3
// resolving second3
// second3

第一个stream很好且顺序,但是当我用它构建嵌套流时,flatMapConcat不再有效。我需要第一个流来等待第二个流。

1 个答案:

答案 0 :(得分:1)

尝试在第一个内部移动第二个.flatMap

var stream = Bacon.fromArray([1,2,3]).flatMapConcat(function(value) {
  return Bacon.fromPromise(getPromise(value)).flatMapConcat(function(promised) {
    return Bacon.fromPromise(getPromise('second' + promised));
  });
});