gpt4 book ai didi

javascript - 带有嵌套流的 flatMapConcat

转载 作者:行者123 更新时间:2023-12-03 11:06:13 28 4
gpt4 key购买 nike

我在这里询问了“如何将流映射到延迟 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

第一个很好而且是连续的,但是当我用它构建嵌套流时,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));
});
});

关于javascript - 带有嵌套流的 flatMapConcat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27847594/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com