我问过“如何将流映射到惰性承诺流”,并发限制为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
不再起作用。我需要第一个流来等待第二个流。 最佳答案
尝试将第二个.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));
});
});