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);
});
};
I am only interested in first post, thus take(1)
, and It should call getPost
once.
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();
However map
returns a promise, while flatMap
returns the post itself. How do I have a lazy stream that returns the value of promise?