将流映射到惰性承诺流 [英] map a stream to lazy promise stream
问题描述
我有一个我有一个数字流,我必须使用承诺将它们变成一个帖子流.我想懒惰地这样做.所以如果我从帖子流中做 .take(1)
,它只会把一个数字变成一个帖子.
I have a I have a stream of numbers, I have to turn them into a stream of posts using a promise. And I want to do this lazily. So if I do .take(1)
from the post stream, it will turn only one number to a post.
这是从数字中获取帖子的承诺:
This is the promise that gets a post from a number:
var getPost = function(author) {
console.log('get post' + author);
return new RSVP.Promise(function(resolve, reject) {
setTimeout(function() {
var result = "Post by " + author;
resolve(result);
}, 1000);
});
};
我只对第一篇文章感兴趣,因此take(1)
,它应该调用一次getPost
.
I am only interested in first post, thus take(1)
, and It should call getPost
once.
如果我使用 map
,流会延迟工作,调用 getPost
一次.如果我使用 flatmap
,它会为所有数字调用 getPost
.
If I use map
, the stream works lazy, calls getPost
once. If I use flatmap
, it calls getPost
for all the numbers.
var lazyStream = Bacon.fromArray([1, 2, 3, 4]).map(function(value) {
return Bacon.fromPromise(getPost(value));
});
var nonLazyStream = Bacon.fromArray([1, 2, 3, 4]).flatMap(function(value) {
return Bacon.fromPromise(getPost(value));
});
lazyStream.take(2).log();
//nonLazyStream.take(2).log();
然而map
返回一个promise,而flatMap
返回post 本身.我如何拥有一个返回 promise 值的惰性流?
However map
returns a promise, while flatMap
returns the post itself. How do I have a lazy stream that returns the value of promise?
推荐答案
flatMap
一次性获取由 Promise 创建的所有流,并一次使用所有流生成一个新流.现场你已经观察到这并不懒惰,并且会立即调用所有承诺返回函数.
flatMap
takes all the streams created by the promises at once and spawns a new stream using all of the streams at once. Live you have observed this is not lazy and will call all the promise returning functions at once.
您希望一次发生一个,因此您应该使用 flatMapConcat
.它不是一次获取所有流,而是一次一个地调用它们,一个一个地调用承诺 - 这是您通常希望 .flatMap
在其他一些 FRP 库中执行的操作.请注意,如果您曾经使用 flatMapWithConcurrencyLimit
需要它一次做 n
.
You want that to happen one at a time so you should use flatMapConcat
. Instead of taking all the streams at once it will call them one at a time invoking the promises one by one - this is what you'd normally expect .flatMap
to do in some other FRP libraries. Note that this generalizes using flatMapWithConcurrencyLimit
if you ever need it to do n
at a time.
这是一个使用 flatMapConcat
的示例对于类似的情况:
Here is an example using flatMapConcat
for a similar case:
function delayPromise(val){ // delayed promise simulating an async request
return new Promise(function(resolve){
setTimeout(function(){ console.log("Resolve timeout"); resolve(val); }, 500);
});
}
var stream = Bacon.fromArray([1, 2, 3, 4]).flatMapConcat(function(value) {
return Bacon.fromPromise(delayPromise(value));
});
stream.take(1).log();
这篇关于将流映射到惰性承诺流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!